94 条题解
-
0
-
0
这道题目是一道递推题,需要找到数列的规律,然后根据规律递推出第n项的值。
我们可以发现,数列中每一项都是前三项之和。那么我们可以用a、b、c三个变量来表示前三项,用ans表示当前项的值,然后用一个for循环从第四项开始递推到第n项,每次更新前三项的值,并根据前三项的值求出当前项的值。
具体来说,我们可以将前三项初始化为1,即a=1,b=1,c=1,第一项、第二项、第三项都是1。然后从第四项开始,用ans=a+b+c求出当前项的值,然后更新前三项,即a=b,b=c,c=ans。最后输出第n项的值即可。
代码如下:
#include <iostream> using namespace std; int main() { int n; cin >> n; int a = 1, b = 1, c = 1; // 前三项 int ans = 1; for (int i = 4; i <= n; i++) { ans = a + b + c; // 每一项都是前三项之和 a = b; b = c; c = ans; // 更新前三项 } cout << ans << endl; // 输出第n项 return 0; }
-
0
先给出代码:
#include <bits/stdc++.h> #define int long long using namespace std; int n; int dfs(int x) { if(x==1 ||x==2 || x==3)return 1; return dfs(x-1)+dfs(x-2)+dfs(x-3); } signed main() { cin>>n; cout<<dfs(n); return 0; }
思路:
其实这就是一个简单的找规律而已。
1,1,1,3,5,9,17,31,57,105,……
先看第四项,它是前三项的和;
再看第五项,它是第2,3,4项的和;
再看第x项,它是第x-1,x-2,x-3的和。
-
0
AC供大家参考
#include <iostream>//hetao3097453 using namespace std; int fib(int n) { if(n == 1) { return 1; } else if(n == 2) { return 1; } else if(n == 3) { return 1; } else { return fib(n - 1) + fib(n - 2) + fib(n - 3); } } int main() { int n; cin >> n; cout << fib(n) << endl; return 0; }
-
0
思路
这道题的难度在于找到数列规律。 $\\$(1)不难发现从数列的第4项开始,每一项都等于它的前3项和,所以得到递归表达式: $\\f(n)=f(n-1)+f(n-2)+f(n-3)$ $\\$(2)那么终止条件也就是显然的,前3项都无法向前查找3项,都初始化为1.代码
#include<iostream> using namespace std; int n; int func(int x) { if (x <= 3) return 1; return func(x - 1) + func(x - 2) + func(x - 3); } int main() { cin >> n; cout << func(n); }
-
-1
~~#include <iostream>//hetao3097453 using namespace std; int fib(int n) { if(n == 1) { return 1; } else if(n == 2) { return 1; } else if(n == 3) { return 1; } else { return fib(n - 1) + fib(n - 2) + fib(n - 3); } } int main() { int n; cin >> n; cout << fib(n) << endl; return 0; } ~~
信息
- ID
- 5
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 5
- 标签
- 递交数
- 6686
- 已通过
- 2803
- 上传者