博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] 518. Coin Change 2
阅读量:6200 次
发布时间:2019-06-21

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

Problem

You are given coins of different denominations and a total amount of money. Write a function to compute the number of combinations that make up that amount. You may assume that you have infinite number of each kind of coin.

Note: You can assume that

0 <= amount <= 5000

1 <= coin <= 5000
the number of coins is less than 500
the answer is guaranteed to fit into signed 32-bit integer

Example 1:Input: amount = 5, coins = [1, 2, 5]Output: 4Explanation: there are four ways to make up the amount:5=55=2+2+15=2+1+1+15=1+1+1+1+1 Example 2:Input: amount = 3, coins = [2]Output: 0Explanation: the amount of 3 cannot be made up just with coins of 2. Example 3:Input: amount = 10, coins = [10] Output: 1

Solution

DP

class Solution {    public int change(int amount, int[] coins) {        int[] dp = new int[amount+1];        dp[0] = 1;        for (int coin: coins) {            for (int i = 1; i <= amount; i++) {                if (i - coin >= 0) dp[i] += dp[i-coin];            }        }        return dp[amount];    }}

DFS - TLE

class Solution {    int count = 0;    public int change(int amount, int[] coins) {        if (amount == 0) return 1;        dfs(coins, 0, 0, amount);        return count;    }    private void dfs(int[] coins, int start, int sum, int amount) {        if (start == coins.length) return;        if (sum == amount) {            count++;            return;        }        for (int i = start; i < coins.length; i++) {            if (coins[i] + sum > amount) continue;            else dfs(coins, i, sum+coins[i], amount);        }    }}

转载地址:http://hkxca.baihongyu.com/

你可能感兴趣的文章
Oracle如何删除表中重复记录
查看>>
nginx 是如何处理访问请求的
查看>>
wget参数用法详解
查看>>
使用curl命令查看访问url的时间
查看>>
python添加环境变量
查看>>
DP-01背包 (题)
查看>>
WinForm中跨线程操作控件
查看>>
CODING 敏捷实践完全指南
查看>>
unittest测试框架和测试报告的输出实例(一)
查看>>
下MFC中对象、句柄、ID之间的区别.
查看>>
如何构建Win32汇编的编程环境(ONEPROBLEM个人推荐)
查看>>
Asp.Net MVC 分页、检索、排序整体实现
查看>>
Flymeos插桩适配教程
查看>>
还在用PS磨皮去皱?看看如何用神经网络高度还原你的年轻容貌!
查看>>
大端模式与小端模式、网络字节顺序与主机字节顺序
查看>>
微信支付申请90%的商户都卡在这儿了,申请微信支付,商户功能设置详细说明...
查看>>
制作一款微信表情
查看>>
高仿Instagram 页面效果android特效
查看>>
我的友情链接
查看>>
Juniper 基于路由的×××
查看>>