LeetCode | Climbing Stairs(爬樓梯)
阿新 • • 發佈:2019-02-17
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?
題目解析:這道題說白了是遞迴,更好點是動態規劃,要求n,從n-1和n-2來。a[i] = a[i-1] + a[i-2]。本來想設一個數組,但由於只涉及到兩個數之間的求和,並且是相鄰的兩個數,就沒必要去設陣列了,只用兩個變數即可。
class Solution { public: int climbStairs(int n) { if(n == 1 || n== 2) return n; int temp1 = 1; int temp2 = 2; for(int i = 3;i <= n;i++){ int temp = temp1+temp2; temp1 = temp2; temp2 = temp; } return temp2; } };