Swift DP硬币更换算法-从表中检索硬币组合
为了找出我们有多少种方法可以改变硬币的数量,我们可以创建一个DP算法,生成下表:Swift DP硬币更换算法-从表中检索硬币组合,swift,dynamic-programming,coin-change,Swift,Dynamic Programming,Coin Change,为了找出我们有多少种方法可以改变硬币的数量,我们可以创建一个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],[2,1],[2,2],[3,1] 我的问题是,是否可以从我刚刚生成的表中检索这些组合?怎么做 为了完整起见,
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],[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];
}
func硬币兑换(硬币:[Int],金额:Int)->Int{
//整数[金额+1][硬币]
变量表=数组(重复:数组(重复:0,计数:coins.count),计数:amount+1)
对于0中的i.当然可以。我们定义了一个新函数get_solution(i,j)
,这意味着表[i][j]的所有解决方案
。
您可以认为它返回一个数组数组,例如,get_solution(4,3)
的输出是[[1,1,1],[2,1],[2,2],[3,1]
。然后:
- 案例1。来自
获取解决方案(i-硬币[j],j)
的任何解决方案加上硬币[j]
是表[i][j]
的解决方案
- 案例2。来自
get_解决方案(i,j-1)
的任何解决方案都是表[i][j]
的解决方案
您可以证明案例1+案例2是表[i][j]
的所有可能解决方案(注意,通过这种方式您可以得到表[i][j]
)
剩下的唯一问题是实现get_solution(i,j)
,我认为自己做这件事对你有好处
如果您还有任何问题,请不要犹豫,在这里留下评论。太棒了,它成功了!我的结果代码很难看,但现在我了解了解决方案,我可以做得更好。我用函数编辑了问题。谢谢:)
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)
}