• LF.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> sol = new ArrayList<>();
        dfs(target, coins, res, 0 , sol) ;
        return res;
      }
    
      private void dfs(int remain, int[] coins,List<List<Integer>> res, int index, List<Integer> sol){
        //base case
        if (index == coins.length) {
            if (remain == 0 ) {
                res.add(new ArrayList<>(sol));
            }
            return ;
        }
        //当前的coin 能用几次用几次的往下压: 因为次数从0开始, 所以需要 <=
        for (int i=0 ; i<= remain/coins[index]; i++ ) {
            sol.add(i) ;
            dfs(remain-i*coins[index], coins, res, index+1, sol);
            sol.remove(sol.size()-1);
        }
      }
    }
  • 相关阅读:
    ES6新特性概览
    JavaScript一些不常用的写法
    使用HTML5的十大原因
    利用HTML5开发Android(7)---HTML5本地存储之Database Storage
    利用HTML5开发Android(6)---构建HTML5离线应用
    利用HTML5开发Android(5)---HTML5地理位置服务在Android中的应用
    利用HTML5开发Android(4)---HTML5本地存储之Web Storage
    利用HTML5开发Android(3)---Android中的调试
    利用HTML5开发Android(2)---Android中构建HTML5应用
    javascript中的prototype和constructor
  • 原文地址:https://www.cnblogs.com/davidnyc/p/8689814.html
Copyright © 2020-2023  润新知