LeetCode OJ算法题(七十):Climbing Stairs

来源:互联网 发布:苹果mac在哪里升级 编辑:程序博客网 时间:2024/05/16 10:47

题目:

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?

解法:

采用DP算法,找到递推关系式。

假设到第n个台阶有f(n)种走法,那么f(n) = f(n-1)+f(n-2),因为前一步不是在第n-1个台阶上,就是在第n-2个台阶上。用一张n*1的表存储f(n),注意n=1和n=2时的初始值分别为1和2,。

public class No70_ClimbingStairs {public static void main(String[] args){System.out.println(climbStairs(5));//f(n) = f(n-1)+ f(n-2);}public static int climbStairs(int n) {if(n==0 || n==1 || n==2) return n;        int[] result = new int[n+1];        result[0] = 0;        result[1] = 1;        result[2] = 2;        for(int i=3;i<n+1;i++){        result[i] = result[i-1] + result[i-2];        }        return result[n];    }}


0 0