LeetCode70 Climbing Stairs

LeetCode70 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.

簡單分析

這道題是比較經典的動態規劃的題目,爬樓梯。採用動態規劃的算法。動態規劃的變量保存當前階梯和上一階梯的可行解,

代碼如下


public int climbStairs(int n) {
    int [] dp= new int[2];
    dp[0]=1;
    dp[1]=1;
    for(int i=2;i<=n;i++){
        dp[i&1]+=dp[(i+1)&1];
    }
    return dp[n&1];
}

LeetCode學習筆記持續更新

GitHub地址 https://github.com/yanqinghe/leetcode

CSDN博客地址 http://blog.csdn.net/yanqinghe123/article/category/7176678

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章