【发布时间】:2017-03-03 20:25:23
【问题描述】:
要找出在给定硬币[1,2,3] 的情况下我们有多少种方法可以为4 找零,我们可以创建一个生成下表的DP 算法:
table[amount][coins.count]
0 1 2 3 4
-----------
(0) 1 | 1 1 1 1 1
(1) 2 | 1 1 2 2 3
(2) 3 | 1 1 2 3 4
最后一个位置是我们的答案。答案是4,因为我们有以下组合:[1,1,1,1],[2,1],[2,2],[3,1]。
我的问题是,是否可以从我刚刚生成的表中检索这些组合?怎么样?
为了完整起见,这是我的算法
func coinChange(coins: [Int], amount: Int) -> Int {
// int[amount+1][coins]
var table = Array<Array<Int>>(repeating: Array<Int>(repeating: 0, count: coins.count), count: amount + 1)
for i in 0..<coins.count {
table[0][i] = 1
}
for i in 1...amount {
for j in 0..<coins.count {
//solutions that include coins[j]
let x = i - coins[j] >= 0 ? table[i - coins[j]][j] : 0
//solutions that don't include coins[j]
let y = j >= 1 ? table[i][j-1] : 0
table[i][j] = x + y
}
}
return table[amount][coins.count - 1];
}
谢谢!
--
解决方案
根据@Sayakiss 的解释,这是一个检索组合的丑陋函数:
func getSolution(_ i: Int, _ j: Int) -> [[Int]] {
if j < 0 || i < 0 {
//not a solution
return []
}
if i == 0 && j == 0 {
//valid solution. return an empty array where the coins will be appended
return [[]]
}
return getSolution(i - coins[j], j).map{var a = $0; a.append(coins[j]);return a} + getSolution(i, j - 1)
}
getSolution(amount, coins.count-1)
输出:
[[1, 3], [2, 2], [1, 1, 2], [1, 1, 1, 1]]
【问题讨论】:
标签: swift dynamic-programming coin-change