# 动态规划之找零钱问题

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

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) {
if (i - coins[0] > 0)
} else {
if (i - coins[min_] > 0)
}
}
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();
}

}

}


• 本文已收录于以下专栏：

举报原因： 您举报文章：动态规划之找零钱问题 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)