Leetcode:Coin Change 2

来源:互联网 发布:传奇世界翅膀进阶数据 编辑:程序博客网 时间:2024/06/03 23:24

题目:

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: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:

Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:

Input: amount = 10, coins = [10]
Output: 1

思路:

感觉这道题和“爬楼梯~~~”具体名字不记得了,解题思路基本类似,第一印象就是动态规划,公式如下:coins[] 用来存储不同面值的硬币;dp[] 用来保存每总值的结果;dp[i]表示总数钱为i时,有多少种组合方法。可以得到:dp[i] += dp[i-coin[j]]
注意: 这里面还有一个坑,就是组合的重复为题,比如:

5=1+1+1+2
5=2+1+1+1
其实这是一种情况。所以接下来的任务就是去掉重复,去重的思路也是很简单:

如果前面用过的面值,后面就不要再用了。

代码如下:

public class Solution {    public int change(int amount, int[] coins) {        int [] dp = new int[amount+1];        dp[0] = 1;//初始的时候要组合中0元钱,有1中组合方式。        Arrays.sort(coins);//这个排序不是必须的,当时排序是为了好思考问题。        //硬币的面值在外循环,这样保证之前用过的面值不会再被使用        for(int i=0;i<coins.length;i++){            for(int j=coins[i];j<=amount;j++){                dp[j] += dp[j-coins[i]];            }        }        return dp[amount];    }}

运行结果:

这里写图片描述

0 0