zoukankan      html  css  js  c++  java
  • [Algo] 73. Combinations Of Coins

    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

    • coins - an array of positive integers representing the different denominations of coins, there are no duplicate numbers and the numbers are sorted by descending order, eg. {25, 10, 5, 2, 1}
    • target - a non-negative integer representing the target number of cents, eg. 99

    Assumptions

    • coins is not null and is not empty, all the numbers in coins are positive
    • target >= 0
    • You have infinite number of coins for each of the denominations, you can pick any number of the coins.

    Return

    • a list of ways of combinations of coins to sum up to be target.
    • each way of combinations is represented by list of integer, the number at each index means the number of coins used for the denomination at corresponding index.

    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 - 1) {
              if (left % coins[coins.length - 1] == 0) {
                list.add(left / coins[coins.length - 1]);
                res.add(new ArrayList<>(list));
                list.remove(list.size() - 1);
              }
            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);
          } 
        }
    }
  • 相关阅读:
    【matlab】学习笔记 2脚本编写
    【matlab】学习笔记 1 入门简单操作
    【matlab】学习笔记 3 函数编写
    MySQL学习笔记
    数据库连接-----MySQL -> JDBC
    leetcode——Mysql数据库查询题目
    不同单词个数统计
    初始化二维数组
    JS基本变量类型和对象杂谈
    LeetCode Clone Graph
  • 原文地址:https://www.cnblogs.com/xuanlu/p/12316173.html
Copyright © 2011-2022 走看看