4 条题解

  • 6
    @ 2026-6-3 23:02:07
    #include <bits/stdc++.h>
    using namespace std;
    int main() {
    int n;
        cin >> n;
        int a = 1, b = 1;
        if (n == 1 || n == 2)
        {
            cout << 1;
            return 0;
        }
        int r;
        for (int i = 3; i <= n; i++)
        {
            r = a + b;
            a = b;
            b = r;
        }
        cout << r;
        return 0;
    }
        
    
    
    • 0
      @ 2026-6-7 23:21:14

      严禁抄袭,仅供参考!!!

      递归 求斐波那契数列:

      
      #include <bits/stdc++.h>
      using namespace std;
      int x;
      
      long long fib(int a,int b,int n){
      	if(n==x)return b-a;
      	
       	return fib(b,a+b,n+1);
      }
      
      
      int main() {
      	cin>>x;
      	cout<<fib(1,1,0);
      	return 0;
      }
      
      
      • -1
        @ 2026-7-14 11:37:51

        这是一题斐波那契数列

        公式:

        A(n)(当前项)=A(n+1)(前一项)+A(n+2)(前前项)

        样例输入

        6
        
        

        样例输出

        8
        
        

        代码实现

        #include <bits/stdc++.h>
        using namespace std;
        #define int long long
        int n, res;
        int f(int x) {
        	if (x == 1 || x == 2) {
        		res = 1;
        	} else {
        		res = f(x - 1) + f(x - 2);
        	}
        
        	return res;
        }
        
        main(signed) {
        	cin >> n;
        	f(n);
        	cout << res << '\n';
        
        	return 0;
        }
        
        
        
        

        数据更大时:

        样例输入

        50
        
        

        样例输出

        12586269025
        
        

        代码实现

        #include <bits/stdc++.h>
        using namespace std;
        #define int long long
        const int N = 1e6 + 10;
        
        int n, res, a[N] = {0};
        
        main(signed) {
        	cin >> n;
        	a[1] = 1;
        	a[2] = 1;
        
        	for (int i = 3; i <= n; i++) {
        
        		a[i] = a[i - 1] + a[i - 2];
        	}
          //递推(找规律)
        
        	cout << a[n] << '\n';
        
        	return 0;
        }
        

        第一段代码为递归,第二段代码为递推,递归只要数据超过50就会超时。

        • -1
          @ 2026-6-3 20:27:26

          #include <bits/stdc++.h> using namespace std;

          int main() { int n; cin >> n; if (n == 1 || n == 2) { cout << 1 << endl; return 0; } int a = 1; int b = 1; int c;

          for (int i = 3; i <= n; i++) {
          	c = a + b;
          	a = b;
          	b = c;
          }
          cout << b << endl;
          return 0;
          

          }

          • @ 2026-6-3 20:32:06

            这题挺难的,我帮忙把代码输出来了,不会的可以复制过来。

        • 1

        信息

        ID
        30958
        时间
        1000ms
        内存
        256MiB
        难度
        3
        标签
        (无)
        递交数
        70
        已通过
        40
        上传者