受限零钱找零问题的Python和Java转换

huangapple go评论85阅读模式
英文:

Restricted Coin change problem python java conversion

问题

// cs is a list of pairs (c, k) where there's k
// coins of value c.
public static int limitedCoins(int[][] cs, int n) {
    int[] r = new int[n + 1];
    r[0] = 1;
    
    for (int i = 0; i < cs.length; i++) {
        int c = cs[i][0];
        int k = cs[i][1];
        
        int[] rs = r.clone();
        
        for (int j = c; j <= n; j++) {
            rs[j] += rs[j - c];
            // This line effectively performs:
            // r'[j] = sum(r[j - j * c] for j = 0...k)
            // but using rs[] so that the computation is O(1)
            // and in place.
            r[j] += rs[j - c] - (j < c * (k + 1) ? 0 : rs[j - c * (k + 1)]);
        }
    }
    
    return r[n];
}

for (int n = 0; n < 50; n++) {
    System.out.println(n + " " + limitedCoins(new int[][]{{1, 3}, {2, 2}, {5, 3}, {10, 2}}, n));
}
英文:

I have a python function from

https://stackoverflow.com/a/44214566/6301603

Which calculates the amount of possible coin changes. Where each coin has a limited avaibility. I tried to understand it to convert it to java but i failed in the line r= can somebody explain whats happening in this line?

# cs is a list of pairs (c, k) where there&#39;s k
# coins of value c.
def limited_coins(cs, n):
    r = [1] + [0] * n
    for c, k in cs:
        # rs[i] will contain the sum r[i] + r[i-c] + r[i-2c] + ...
        rs = r[:]
        for i in xrange(c, n+1):
            rs[i] += rs[i-c]
            # This line effectively performs:
            # r&#39;[i] = sum(r[i-j*c] for j=0...k)
            # but using rs[] so that the computation is O(1)
            # and in place.
            r[i] += rs[i-c] - (0 if i&lt;c*(k+1) else rs[i-c*(k+1)])
    return r[n]

for n in xrange(50):
    print n, limited_coins([(1, 3), (2, 2), (5, 3), (10, 2)], n)

Thanks

答案1

得分: 0

用以下代码替换那行代码:

int[] r = new int[n+1];
r[0] = 1;
for (int i = 1; i < r.length; i++) 
    r[i] = 0;
英文:

Replace that line with

int[] r = new int[n+1];
r[0] = 1;
for (int i = 1; i &lt; r.length; i++) 
    r[i] = 0;

huangapple
  • 本文由 发表于 2020年10月11日 22:41:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64305272.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定