小乐乐上课需要走n阶台阶,因为他腿比较长,所以每次可以选择走一阶或者走两阶,那么他一共有多少种走法?
#include <iostream>
using namespace std;
int f(int n)//递归思想
{
if(n==1||n==0) return 1;
else return f(n-1)+f(n-2);
}
int main()
{
int n;
cin>>n;
cout<<f(n)<<endl;
return 0;
} #include<bits/stdc++.h>
using namespace std;
int stage[30];
/*
第一种解法:
int main(){
int n;
cin >> n;
int first = 1;
int second = 2;
for(int i = 3; i <= n; i++){
int third = first + second;
first = second;
second = third;
}
cout << second << endl;
return 0;
}
*/
//第二种解法:
int main(){
int n;
cin >> n;
stage[1] = 1;
stage[2] = 2;
for(int i = 3; i <= n; i++){
stage[i] = stage[i - 1] + stage[i - 2];
}
cout << stage[n] << endl;
return 0;
} function z(n){
if(n==1) return 1;
if(n==2) return 2;
return (z(n-1) + z(n-2));
}
var n = parseInt(readline());
console.log(z(n)); #include <stdio.h>
// 斐波那契数列问题
// 思路:递推 + 回归
int main() {
int n;
while (scanf("%d", &n) != EOF) {
int f, tmp, f1 = 0, f2 = 1;
for(int i = 0; i < n; i++)
{
f = f1 + f2;
tmp = f2;
f2 = f1 + f2;
f1 = tmp;
}
printf("%d\n", f);
}
return 0;
}
方案1:斐波那契数列递归
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); System.out.println(method(n)); } public static int method(int n){ if(n==1) return 1; if(n==2) return 2; return method(n-1)+method(n-2); } }
方案2:动态规划
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int[] arr = new int[n]; arr[0] = 1; arr[1] = 2; for(int i = 2; i < arr.length; i++){ arr[i] = arr[i-1]+arr[i-2]; } System.out.println(arr[n-1]); } }
方案3:数组优化
import java.util.*; public class Main{ public static void main(String[] args){ Scanner sc = new Scanner(System.in); int n = sc.nextInt(); int l=1,m=2; int sum; for(int i = 3; i <= n; i++){ sum = l +m; l = m; m = sum; } System.out.println(m); } }
#include <stdio.h>
int walking_ways(int n);
int main(void)
{
int n;
while (scanf("%d", &n) != EOF)
{
printf("%d\n", walking_ways(n));
}
return 0;
}
int walking_ways(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return walking_ways(n - 1) + walking_ways(n - 2);
}
} #走到第一阶只有一种方法:步1; #走到第二阶有两种方法:2*步1和1*步2,; #走到第三阶有两种方法:因为每次可以走一步和两步,则走到第三阶的步数为走到第二阶的方法数和走到第一阶的方法数之和 n=int(input()) a=[1,2] for i in range(2,n): a.extend([a[i-1]+a[i-2]]) print(a[len(a)-1])