Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
先进行列举找到规律;
1 -> 1;
2 -> 2;
3 -> 3;
4 -> 5;
5 -> 8;
6 -> 13;
7 -> 21;
8 -> 34;
9 ->55;
发现
当n>3时,n对应的情况数字为n-1和n-2之和。此时,规律正好和斐波那契数列出现的规律对应(之后有时间会专门针对斐波那契数列写一篇总结,待我看完算导第十九章);
class Solution {
public:
int climbStairs(int n) {
int* A = new int[n +1];
int x;
A[0] = 1;
A[1] = 2;
for (int i = 2; i < n; i++) {
A[i] = A[i - 1] + A[i - 2];
}
x = A[n - 1];
delete[]A;
return x;
}
};
方法二:
没有运用数组;
单纯的来利用数值的传递来实现
class Solution {
public:
int climbStairs(int n) {
if (n == 1) {
return 1;
}
else{
int x = 2;
int y = 1;
int z;
for (int i = 0; i <= n - 3; i++) {
z = x;
x = x + y;
y = z;
}
return x;
}
}
};