題目:假設你須要進入一個房間,可是房間在樓上,你須要走完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