[Algo] 73. Combinations Of Coins

时间:2020-02-16 11:55:48   收藏:0   阅读:66

Given a number of different denominations of coins (e.g., 1 cent, 5 cents, 10 cents, 25 cents), get all the possible ways to pay a target number of cents.

Arguments

Assumptions

Return

Examples

coins = {2, 1}, target = 4, the return should be

[

  [0, 4],   (4 cents can be conducted by 0 * 2 cents + 4 * 1 cents)

  [1, 2],   (4 cents can be conducted by 1 * 2 cents + 2 * 1 cents)

  [2, 0]    (4 cents can be conducted by 2 * 2 cents + 0 * 1 cents)

]

 

public class Solution {
  public List<List<Integer>> combinations(int target, int[] coins) {
    // Write your solution here
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> list = new ArrayList<>();
    helper(res, list, 0, coins, target);
    return res;
  }

    private void helper(List<List<Integer>> res, List<Integer> list, int index, int[] coins, int left) {
    if (index == coins.length) {
        if (left == 0) {
          res.add(new ArrayList<>(list));
      }
      return;
    }
    for (int i = 0; i <= left/coins[index]; i++) {
      list.add(i);
      helper(res, list, index + 1, coins, left - i * coins[index]);
      list.remove(list.size() - 1);
    }
  }
}

 

原文:https://www.cnblogs.com/xuanlu/p/12316173.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!