您的位置:首页 > 大数据 > 人工智能

[Leetcode]-Climbing Stairs

2015-07-06 10:57 288 查看
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
 = 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: