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

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

Restricted Coin change problem python java conversion

问题

  1. // cs is a list of pairs (c, k) where there's k
  2. // coins of value c.
  3. public static int limitedCoins(int[][] cs, int n) {
  4. int[] r = new int[n + 1];
  5. r[0] = 1;
  6. for (int i = 0; i < cs.length; i++) {
  7. int c = cs[i][0];
  8. int k = cs[i][1];
  9. int[] rs = r.clone();
  10. for (int j = c; j <= n; j++) {
  11. rs[j] += rs[j - c];
  12. // This line effectively performs:
  13. // r'[j] = sum(r[j - j * c] for j = 0...k)
  14. // but using rs[] so that the computation is O(1)
  15. // and in place.
  16. r[j] += rs[j - c] - (j < c * (k + 1) ? 0 : rs[j - c * (k + 1)]);
  17. }
  18. }
  19. return r[n];
  20. }
  21. for (int n = 0; n < 50; n++) {
  22. System.out.println(n + " " + limitedCoins(new int[][]{{1, 3}, {2, 2}, {5, 3}, {10, 2}}, n));
  23. }
英文:

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?

  1. # cs is a list of pairs (c, k) where there&#39;s k
  2. # coins of value c.
  3. def limited_coins(cs, n):
  4. r = [1] + [0] * n
  5. for c, k in cs:
  6. # rs[i] will contain the sum r[i] + r[i-c] + r[i-2c] + ...
  7. rs = r[:]
  8. for i in xrange(c, n+1):
  9. rs[i] += rs[i-c]
  10. # This line effectively performs:
  11. # r&#39;[i] = sum(r[i-j*c] for j=0...k)
  12. # but using rs[] so that the computation is O(1)
  13. # and in place.
  14. r[i] += rs[i-c] - (0 if i&lt;c*(k+1) else rs[i-c*(k+1)])
  15. return r[n]
  16. for n in xrange(50):
  17. print n, limited_coins([(1, 3), (2, 2), (5, 3), (10, 2)], n)

Thanks

答案1

得分: 0

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

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

Replace that line with

  1. int[] r = new int[n+1];
  2. r[0] = 1;
  3. for (int i = 1; i &lt; r.length; i++)
  4. 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:

确定