您的位置:首页 > 其它

Recursion 爬楼梯问题 @CareerCup

2013-11-26 09:16 459 查看
开始CareerCup一书的刷题。。先从recursion这一章开始!

我的解法:

package Recursion;

/**
* A child is running up a staircase with n steps, and can hop either 1 step, 2
* steps, or 3 steps at a time. Implement a method to count how many possible
* ways the child can run up the stairs.
*
* 一个小孩往上爬一个n层的台阶,他每次可以爬1层,2层或3层。
* 实现一个方法来计算小孩有有多少种方式爬上台阶
*
*/
public class S9_1 {

public static void main(String[] args) {
for (int i = 0; i < 30; i++) {
System.out.println(countWaysRec(i));
System.out.println(countWaysDP(i));
}
}

public static int countWaysRec(int n){
if(n == 0){
return 1;
}
if(n == 1){
return 1;
}
if(n == 2){
return 2; // 1个2 或者 2个1
}
if(n == 3){
return 4; // (1个3) 或 (1个1,1个2)或(1个2,1个1)或(3个1)
}

return countWaysRec(n-1) + countWaysRec(n-2) + countWaysRec(n-3);
}

public static int countWaysDP(int n){
int[] ways = new int[n+1];
if(n == 0){
return 1;
}
if(n == 1){
return 1;
}
if(n == 2){
return 2; // 1个2 或者 2个1
}
if(n == 3){
return 4; // (1个3) 或 (1个1,1个2)或(1个2,1个1)或(3个1)
}
ways[0] = 1;
ways[1] = 1;
ways[2] = 2;
ways[3] = 4;
for(int i=4; i<=n; i++){
ways[i] = ways[i-1] + ways[i-2] + ways[i-3];
}
return ways
;
}

}


官方解法:
package Question9_1;

import java.util.HashMap;

/**
* A child is running up a staircase with n steps, and can hop either 1 step, 2 steps,
or 3 steps at a time. Implement a method to count how many possible ways the
child can run up the stairs.
*
*/
public class Question {

public static int countWaysDP(int n, HashMap<Integer, Integer> map) {
if (map.containsKey(n)) {
return map.get(n).intValue();
}
int q = 0;
if (n < 0) {
return 0;
}
if (n == 0) {
q = 1;
} else {
q = countWaysDP(n - 1, map) + countWaysDP(n - 2, map) + countWaysDP(n - 3, map);
}
map.put(n, q);
return q;
}

public static int countWaysRecursive(int n) {
if (n < 0) {
return 0;
} else if (n == 0) {
return 1;
} else {
return countWaysRecursive(n - 1) + countWaysRecursive(n - 2) + countWaysRecursive(n - 3);
}
}

public static void main(String[] args) {
for (int i = 0; i < 30; i++) {
long t1 = System.currentTimeMillis();
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
int c1 = countWaysDP(i, map);
long t2 = System.currentTimeMillis();
long d1 = t2 - t1;

long t3 = System.currentTimeMillis();
int c2 = countWaysRecursive(i);
long t4 = System.currentTimeMillis();
long d2 = t4 - t3;
System.out.println(i + " " + c1 + " " + c2 + " " + d1 + " " + d2);
System.out.println(c2);
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: