动态规划之找零钱问题
import java.util.ArrayList;

public class Coin {
	/**
	 * 凑够sum至少需要多少coin
	 * @param coins coin面值
	 * @param sum
	 * @return
	 */
	public static int[] getLeastNum(int[] coins, int sum) {
		int[] d = new int[sum + 1];
		d[0] = 0;
		
		for (int i = 1; i <= sum; i++) {
			int min = i - coins[0] >= 0 ? d[i - coins[0]] + 1 : 0;
			for (int j = 1; j < coins.length; j++) {
				if ((i - coins[j]) >= 0 && min > d[i - coins[j]] + 1) {
					min = d[i - coins[j]] + 1;
				}
			}
			d[i] = min;
		}
		return d;
	}
	
	public static ArrayList<Integer>[] getLeastNumAndValue(int[] coins, int sum) {
		ArrayList[] ret = new ArrayList[sum + 1];
		
		for (int i = 0; i < ret.length; i++) {
			ret[i] = new ArrayList<Integer>();
		}
		ret[0].add(0);
		
		int[] d = new int[sum + 1];
		d[0] = 0;
		
		for (int i = 1; i <= sum; i++) 
		{
			int min = i - coins[0] >= 0 ? d[i - coins[0]] + 1 : 0;
			boolean flag = true;
			int j = 1;
			int min_ = 1;
			for (; j < coins.length; j++) 
			{
				if ((i - coins[j]) >= 0 && min >= d[i - coins[j]] + 1) 
				{
					min = d[i - coins[j]] + 1;
					min_ = j;
					flag = false;
				}
			}
			d[i] = min;
			if (flag) {
				ret[i].add(coins[0]);
				if (i - coins[0] > 0)
					ret[i].addAll(ret[i - coins[0]]);
			} else {
				ret[i].add(coins[min_]);
				if (i - coins[min_] > 0)
					ret[i].addAll(ret[i - coins[min_]]);
			}
		}
		return ret;
	}
	
	public static void main(String[] args) {
		int coins[] = {1, 3, 5};
		int[] ret = getLeastNum(coins, 21);
		ArrayList<Integer>[] nums = getLeastNumAndValue(coins, 21);
		for (int i = 1; i < ret.length; i++) {
			System.out.print("i = " + i + "  value = " + ret[i] + "  nums = ");
			ArrayList<Integer> r = nums[i];
			for (int j = 0; j < r.size(); j++) {
				System.out.print(r.get(j) + " ");
			}
			System.out.println();
		}
		
	}

}

参考网址:http://www.360doc.com/content/13/0601/00/8076359_289597587.shtml

                   http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741374.html

阅读更多
个人分类: 算法
想对作者说点什么? 我来说一句

找零钱-动态规划

问题

jiyanfeng1 jiyanfeng1

2014-10-28 22:27:15

阅读数:4824

没有更多推荐了,返回首页

不良信息举报

动态规划之找零钱问题

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭