Skip to content

Commit 542cf44

Browse files
Add files via upload
1 parent eb148a6 commit 542cf44

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// 第一种比较慢的思路
2+
// Runtime: 292 ms, faster than 19.15% of C++ online submissions for Length of Longest Fibonacci Subsequence.
3+
// Memory Usage: 9.5 MB, less than 85.71% of C++ online submissions for Length of Longest Fibonacci Subsequence.
4+
5+
class Solution
6+
{
7+
public:
8+
int lenLongestFibSubseq(vector<int>& input)
9+
{
10+
// 边界条件处理
11+
if (input.size() <= 2)
12+
return input.size();
13+
14+
unordered_set<int> hashset(input.begin(), input.end());
15+
16+
int maxLength = 0;
17+
for (int i = 0; i < input.size(); ++i)
18+
{
19+
for (int j = i + 1; j < input.size(); ++j)
20+
{
21+
int curLength = 2;
22+
23+
int a = input[i];
24+
int b = input[j];
25+
26+
while (hashset.find(a + b) != hashset.end())
27+
{
28+
b = a + b;
29+
a = b - a;
30+
++curLength;
31+
}
32+
33+
maxLength = max(maxLength, curLength);
34+
}
35+
}
36+
return maxLength >= 3 ? maxLength : 0;
37+
}
38+
};
39+
40+
41+
42+
// 第二种思路,使用动态规划进行加速 dp[i][j] 代表着以索引为i和j的元素为最后两位的斐波那契数列的最大长度
43+
// Runtime: 252 ms, faster than 23.11% of C++ online submissions for Length of Longest Fibonacci Subsequence.
44+
// Memory Usage: 62.4 MB, less than 14.29% of C++ online submissions for Length of Longest Fibonacci Subsequence.
45+
class Solution
46+
{
47+
public:
48+
int lenLongestFibSubseq(vector<int>& input)
49+
{
50+
// 边界条件处理
51+
if (input.size() <= 2) return 0;
52+
53+
int size = input.size();
54+
vector<vector<int>> dp(size, vector<int>(size, 2));
55+
unordered_map<int, int> hashmap;
56+
57+
int maxLength = 0;
58+
for (int j = 0; j < input.size(); ++j)
59+
{
60+
hashmap.insert(pair<int, int>(input[j], j));
61+
for (int i = 0; i < j; ++i)
62+
{
63+
int a = input[i], b = input[j];
64+
65+
if (hashmap.find(b - a) != hashmap.end() && hashmap.at(b - a) < i)
66+
dp[i][j] = max(dp[hashmap.at(b - a)][i] + 1, dp[i][j]);
67+
68+
maxLength = max(maxLength, dp[i][j]);
69+
}
70+
}
71+
return maxLength >= 3 ? maxLength : 0;
72+
}
73+
};

0 commit comments

Comments
 (0)