JobHunting版 - Given coins of value {k1, k2, ..., km}, 用最少硬币数组成一个sum 咋做啊 |
|
|
|
|
|
i******t 发帖数: 22541 | | z*******3 发帖数: 13709 | | s***5 发帖数: 2136 | 3 这不最basic的DP吗?
【在 i******t 的大作中提到】![](/moin_static193/solenoid/img/up.png) : dp方法
| Y********f 发帖数: 410 | 4 可以重复吗?如果允许重复的话就是bfs
不允许重复用dp,记录当前能够对应每个数的最少硬币数和最后一个硬币
【在 i******t 的大作中提到】![](/moin_static193/solenoid/img/up.png) : dp方法
| b******7 发帖数: 92 | 5 完全背包问题
f(i,v) = min{f(i-1,v), f(i-1,v - k[i])+1}
f(i,v) 用f(v)表示
初始f(v) = MAX_INT (v = 1,..., sum), f(0) = 0
for i = 0 ... m-1
for v = 1...sum
if v >= k[i] and f(v-k[i]) + 1 < f(v)
f(v) = f(v-k[i]) + 1
return f(sum)
参见:三种背包问题http://www.wutianqi.com/?p=539 | r****7 发帖数: 2282 | 6 bfs怎么解?
【在 Y********f 的大作中提到】![](/moin_static193/solenoid/img/up.png) : 可以重复吗?如果允许重复的话就是bfs : 不允许重复用dp,记录当前能够对应每个数的最少硬币数和最后一个硬币
| j**7 发帖数: 143 | 7 public static int minCoinsFor(int[] denom, int total) {
int[][] choice = new int[denom.length + 1][total + 1];
int[][] DP = new int[denom.length + 1][total + 1];
DP[denom.length][0] = 0;
for (int i = 1; i <= total; i++) {
DP[denom.length][i] = -1;
}
for (int i = denom.length - 1; i >= 0; i--) {
for (int j = 0; j <= total; j++) {
int min = -1;
for (int k = 0; k * denom[i] <= j; k++) {
int temp = DP[i + 1][j - k * denom[i]];
if (temp != -1) {
temp = temp + k;
if (min == -1) {
choice[i][j] = k;
min = temp;
} else if (temp < min) {
min = temp;
choice[i][j] = k;
}
}
}
DP[i][j] = min;
}
}
int min = DP[0][total];
if (min != -1) {
for (int i = 0; i < denom.length; i++) {
if (choice[i][total] != 0) {
System.out.print(choice[i][total] + ":" + denom[i] + "s
");
total = total - choice[i][total] * denom[i];
}
}
System.out.println();
}
return min;
} | r**h 发帖数: 1288 | 8 不需要ls这么复杂啊,1D的经典多重背包问题
a = [1, 3, 5, 7, 9]
num = [9999 for i in range(30)]
num[0] = 0
for coin in a:
i = coin
while i<30:
if num[i-coin]+1 < num[i]:
num[i] = num[i-coin]+1
i = i+1
print(num) |
|
|
|
|
|
|