Recursion 爬楼梯问题 @CareerCup

开始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[n];
	}

}

官方解法:

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);
		}
	}

}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值