70. 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?
Note: Given n will be a positive integer.
Example 1:
=
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1.1 step + 1 step
2.2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1.1 step + 1 step + 1 step
2.1 step + 2 steps
3.2 steps + 1 step
解法
动态规划的经典问题,想明白以后会发现跟斐波拉切数列是同一个问题
考虑只差一步就走到第n个台阶时会出现的情况:
- 在第n-1级台阶上,再走一步(假设到这里有X种走法)
- 在第n-2级台阶上,再走两步(假设到这里有Y种走法)
所以走完这个n级台阶就有X+Y种走法
F(N)=F(N-1)+F(N-2)
边界是走到第一级台阶和第二级台阶为1和2
用动态规划思路求解的话只需要知道要求值的前两个值即可,其实连数组都不需要
class Solution {
public int climbStairs(int n) {
if(n==1) return 1;
if(n==2) return 2;
int a=1;
int b=2;
int tmp=0;
for(int i=3;i<=n;i++)
{
tmp=a+b;
a=b;
b=tmp;
}
return tmp;
}
}
如果是数组的话
class Solution {
public int climbStairs(int n) {
if(n==1) return 1;
if(n==2) return 2;
int tmp=0;
int arr[] = new int[n];
arr[0]=1;
arr[1]=2;
for(int i=3;i<=n;i++)
{
arr[i]=arr[i-1]+arr[i-2];
}
return arr[n];
}
}
有参考的文章:
http://www.sohu.com/a/153858619_466939
学习的视频:
https://www.youtube.com/watch?v=OQ5jsbhAv_M