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?
Hide Tags: Dynamic Programming
题目:爬楼梯,需要爬到第N步,每次你可以爬层2步或者1步,问总共有几种方法?
思路:Dynamic Programming(动态规划)
//DP(Dynamic Programming) algorithms 见算法导论
//S[n] = S[n-1] + S[n-2] ;
//S[1] = 1 ;
//S[2] = 2 ;
int climbStairs(int n) {
if( n == 0) return 0;
if( n == 1) return 1;
if( n == 2) return 2;
int one_step = 1;
int two_step = 2;
int sum_ways = 0;
int i = 0 ;
for(i=2;i<n;i++)
{
sum_ways = one_step + two_step;
one_step = two_step;
two_step = sum_ways;
}
return sum_ways;
}