【发布时间】:2014-04-04 16:51:25
【问题描述】:
对于以下问题,我实现了递归和递归动态解决方案,但是 我对迭代解决方案感兴趣(不是递归的)。谁能帮我解决这个问题?
问题:
一只猫在有 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
【问题讨论】:
-
提示:看起来这归结为
f(n) = f(n-1) + f(n-2) + f(n-3),具有合适的起始条件。通过从 1 开始并使用 3 个变量或 3 元素数组来保留一些先前的结果,这很容易计算。 -
正如@ajb 所写,它只是一个更复杂的斐波那契数列。我不会选择 3 个变量,尽管它们就足够了,因为它感觉有点复杂。当数组中的所有先前都可用时,计算
n步骤的值非常简单。不要试图衡量需要多长时间。 ;)
标签: java performance recursion dynamic-programming