动态规划--上楼梯

题目:假设你须要进入一个房间,可是房间在楼上,你须要走完n阶台阶,才能到楼上,若是你一次性能够走一、2或3个台阶,能够计算出你一共有多少种方案去走完全部的台阶进入房间呢?算法

 

解题思路:定义一个状态函数f(n)用来表示若是要走n阶台阶一共能够有方案数量,则f(n)=f(n-1)+f(n-2)+f(n-3)。当n=1时只有一中方案,当n=2时有两种方案(1,1;2),当n=3时有4种方案(1,1,1;1,2;2,1;3),依次类推。函数

 

具体算法(Java版)spa

 1 /**
 2  * 计算n个台阶一共有多少种走法
 3  */
 4 public class Step {
 5 
 6     public static int walk(int n, int[] stepWays) {
 7         if (n <= 0)
 8             return 0;
 9         int count = 0;
10         for (int i = 0; i < stepWays.length; i++) {
11             if (n == stepWays[i]) {
12                 count += 1;
13             } else {
14                 count += walk(n - stepWays[i], stepWays);
15             }
16         }
17         return count;
18     }
19 
20     public static void main(String[] args) {
21         int[] stepWays = new int[] { 3, 1, 2};
22         int n = 10;
23         System.out.println(walk(n, stepWays));
24     }
25 
26 }

 

若是有什么问题,能够一块儿交流! code

相关文章
相关标签/搜索