博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Combinations Of Coins - Medium
阅读量:6159 次
发布时间:2019-06-21

本文共 2090 字,大约阅读时间需要 6 分钟。

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)

]

 

DFS

一共分 n = coins.length 层,每层的分叉数为 amountLeft / coins[i]

time: O(k ^ n),   -- n = amount / min(element of coins), k - length of coins

space: O(k ^ n)

public class Solution {  public List
> combinations(int target, int[] coins) { // Write your solution here List
> res = new ArrayList<>(); dfs(target, coins, 0, new ArrayList<>(), res); return res; } private void dfs(int targetLeft, int[] coins, int index, List
list, List
> res) { if(index == coins.length - 1) { if(targetLeft % coins[index] == 0) { list.add(targetLeft / coins[index]); res.add(new ArrayList<>(list)); list.remove(list.size() - 1); } return; } int max = targetLeft / coins[index]; for(int i = 0; i <= max; i++) { list.add(i); dfs(targetLeft - i * coins[index], coins, index + 1, list, res); list.remove(list.size() - 1); } }}

 

转载于:https://www.cnblogs.com/fatttcat/p/10290471.html

你可能感兴趣的文章
设计模式:组合模式(Composite Pattern)
查看>>
ContentValues 和HashTable区别
查看>>
LogicalDOC 6.6.2 发布,文档管理系统
查看>>
给PowerShell脚本传递参数
查看>>
实战2——Hadoop的日志分析
查看>>
利用FIFO进行文件拷贝一例
查看>>
Ecshop安装过程中的的问题:cls_image::gd_version()和不支持JPEG
查看>>
resmgr:cpu quantum等待事件
查看>>
一个屌丝程序猿的人生(六十六)
查看>>
Java 编码 UTF-8
查看>>
SpringMVC实战(注解)
查看>>
关于静态属性和静态函数
查看>>
进程的基本属性:进程ID、父进程ID、进程组ID、会话和控制终端
查看>>
spring+jotm+ibatis+mysql实现JTA分布式事务
查看>>
MyBatis启动:MapperStatement创建
查看>>
调查问卷相关
查看>>
eclipse启动无响应,老是加载不了revert resources,或停留在Loading workbench状态
查看>>
1. Git-2.12.0-64-bit .exe下载
查看>>
怎样关闭“粘滞键”?
查看>>
[转]React 教程
查看>>