[英]Looking for an iterative solution of a recursive one
對於以下問題,我同時實現了遞歸和遞歸動態解決方案,但是我對迭代解決方案 (而不是遞歸) 感興趣 。 有人可以幫我嗎?
題:
貓正爬上n步的樓梯,一次可以跳1步,2步或3步。 實現一種方法來計算貓可以跳上樓梯的可能方式。
對於迭代解決方案,我所知道的是,我們基本上必須計算下面三叉樹的葉子,其值為0
動態和遞歸解決方案:
import java.util.ArrayList;
public class Question1 {
public static int countAndDisply(int n, ArrayList<Integer> hop) {
if (n<0){
return 0;
}else{
if (n==0) {
for(int i:hop){
System.out.print(i+",");
}
System.out.println();
return 1;
}else{
ArrayList<Integer> hop1 = new ArrayList<>(hop);
hop1.add(1);
ArrayList<Integer> hop2 = new ArrayList<>(hop);
hop2.add(2);
ArrayList<Integer> hop3 = new ArrayList<>(hop);
hop3.add(3);
return countAndDisply(n-1, hop1)+countAndDisply(n-2, hop2)+countAndDisply(n-3, hop3);
}
}
}
/**
* Faster by using dynamic programming techniques to improve speed
* We dont want to calculate the count(n) multiple times!
* @param n
* @param path
* @return
*/
public static int countFast(int n, int[] map){
if (n<0){
return 0;
}else{
if (n==0) {
return 1;
}else{
if (map[n]>0){
return map[n];
}else {
return countFast(n-1, map) + countFast(n-2, map) + countFast(n-3, map);
}
}
}
}
public static int count(int n){
if (n<0){
return 0;
}else{
if (n==0) {
return 1;
}else{
return count(n-1) + count(n-2) + count(n-3);
}
}
}
public static void main(String[] args) {
int n=10;
int [] map = new int[n+1];
long startTime = System.nanoTime();
System.out.println("Total number of possiblilities:"+Question1.countFast(n,map));
long totalTime = System.nanoTime()-startTime;
System.out.println("Time needed for dynamic recursive approach was(ns):"+totalTime);
//System.out.println("Total number of possiblilities:"+Question1.AndDisply(n,new ArrayList<Integer>()));
System.out.println("Total number of possiblilities:"+Question1.count(n));
totalTime = System.nanoTime()-startTime;
System.out.println("Time needed for pure recursive was(ns):"+totalTime);
}
}
這是輸出:
Total number of possiblilities:274
Time needed for dynamic recursive approach was(ns):249311
Total number of possiblilities:274
Time needed for pure recursive was(ns):351088
如果要進行迭代,最好的方法是從0開始,而不是從n開始。
一個例子:
i i-1 i-2 i-3 sum
0 || -1 -2 -3 | 0 # does not contain any solution
1 || 0 -1 -2 | 1 # contains one solution (0)
2 || 1 0 -1 | 2 # contains two solutions (0,1) - (-1,-2)
3 || 2 1 0 | 4 # contains three solutions(0,1,2)
# 2 (2) ,1(1) +1 (0) => 2+1+1 = 4
4 || 3 2 1 | 7 # 3 (4) ,2(2) 1 (1) => 4+2+1 = 7
5 || 4 3 2 | 13 # and so on
6 || 5 4 3 | 24
7 || 6 5 4 | 44
8 || 7 6 5 | 81
9 || 8 7 6 | 149
10 || 9 8 7 | 274
代碼非常簡單:
public static int solve(int n) {
int[] map=new int[n+1];
map[0]=1;
map[1]=1;
map[2]=2;
for (int i = 3; i < map.length; i++) {
map[i]+=map[i-1];
map[i]+=map[i-2];
map[i]+=map[i-3];
}
return map[n];
}
而且當然要快得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.