您的位置:首页 > 其它

动态规划算法求解找硬币问题的递归与非递归实现

2011-04-23 00:03 429 查看
package com.wentora.exercise;
/**
* 求解找硬币最小方案数
* 递归求解
* 非递归求解
* @author wentora
*/
import java.util.Scanner;
public class CoinDynamic {

private int[] coin;

CoinDynamic( int[] coin) {
this.coin = coin;
}

public int getMinMethod(int number) {
if(number <= 0)
return 0;
int temp = 1000;
for(int i = 0; i < coin.length; i++) {
if(number - coin[i] < 0)
continue;
if(getMinMethod(number - coin[i]) <= temp)
temp = getMinMethod(number - coin[i]);
}
return temp + 1;
}

public int dp_getMinMethod(int number) {
int[] count = new int[number + 1];
for(int i = 1; i <= number; i++)
count[i] = 10000;
for(int i = 1; i <= number; i++) {
for(int j = 0; j < coin.length; j++) {
if(coin[j] <= i && count[i] > count[i - coin[j]] + 1)
count[i] = count[i - coin[j]] + 1;
}
}
return count[number];
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in = new Scanner(System.in);
int number;
System.out.print("please input number : ");
number = in.nextInt();
int length;
System.out.print("please input coin size : ");
length = in.nextInt();
int[] coin = new int[length];
System.out.print("please input coin : ");
for(int i = 0; i < length; i++)
coin[i] = in.nextInt();
CoinDynamic cd = new CoinDynamic(coin);
System.out.println("The min is : " + cd.getMinMethod(number));
System.out.print("The min by dp is : " + cd.dp_getMinMethod(number));
}
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  算法 input string class