https://leetcode.com/PRoblems/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?
(1)這道題其實是一道fibonacci數列題。當n=1時,f(n)=1;當n=2時,f(n)=2(有1+1,2這兩種方式);當n>=3時,有f(n)=f(n-1)+f(n-2)(2)但是實現時如果直接使用遞歸,就會超時,所以這里使用循環(3)用f0來記錄f(n-2),用f1來記錄f(n-1),按照之前的公式f(n)=f(n-1)+f(n-2),即得f2=f0+f1;然后更新f0和f1,使得這兩個記錄都往前移動一位,即f0=f1,f1=f2;一共進行n-1次,返回f2
程序代碼public class Solution { public int climbStairs(int n) { int f0 = 1; int f1 = 1; int f2 = n; n--; while (n-- > 0) { f2 = f0 + f1; f0 = f1; f1 = f2; } return f2; }}
算法2-尾遞歸對于這道題,記得之前有本書提到過尾遞歸的思想,所以這里應用了一把尾遞歸,不過單就這道題看來,其實就跟循環的中心思想是一樣的,都是記錄做過的兩個狀態。
程序代碼2public class Solution { public int climbStairsTail(int n, int acc, int acc2) { if (n == 0) { return acc; } return climbStairsTail(n - 1, acc2, acc + acc2); } public int climbStairs(int n) { if (n == 0 || n == 1) { return n; } return climbStairsTail(n, 1, 1); }}
新聞熱點
疑難解答