【问题标题】:DP Coin Change Algorithm - Retrieve coin combinations from tableDP Coin Change Algorithm - 从表中检索硬币组合
【发布时间】: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


    【解决方案1】:

    当然可以。我们定义了一个新函数get_solution(i,j),这意味着您的table[i][j] 的所有解决方案。 你可以认为它返回一个数组数组,例如get_solution(4,3)的输出是[[1,1,1,1],[2,1],[2,2],[3,1]]。那么:

    • 案例 1。get_solution(i - coins[j], j) 加上 coins[j] 的任何解决方案都是 table[i][j] 的解决方案。

    • 案例 2。get_solution(i, j - 1) 的任何解决方案都是 table[i][j] 的解决方案。

    您可以证明案例 1 + 案例 2 是 table[i][j] 的所有可能解决方案(注意您通过这种方式得到 table[i][j])。

    剩下的唯一问题是实现get_solution(i,j),我认为你自己做对你有好处。

    如果您仍有任何问题,请随时在此处发表评论。

    【讨论】:

    • 太棒了,它成功了!我生成的代码很丑陋,但现在我理解了解决方案,我将能够使它变得更好。我用函数编辑了这个问题。谢谢你:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-25
    • 2013-12-09
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多