LeetCode322. Coin Change
2016-02-05 22:09
267 查看
题目链接:
https://leetcode.com/problems/coin-change/题目描述:
给你n种钱币,然后给你一个总数amount,这些钱币可以用无数次,问你用这些钱币组成这个amount,最少的数量是多少?如果不能组成返回-1。Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
思路:
一开始dfs做,果断超时妥妥的。最后发现还是动态规划做吧。dp[i]表示组成数字i需要的最少数量。
dp[i]=min(dp[i-coins[j]]+1,dp[i]);
从前往后找。
代码:
class Solution { public: int coinChange(vector<int>& coins, int amount) { int len=coins.size(); if(len==0){ return -1; } int* dp=new int[amount+1]; dp[0]=0; for(int i=1;i<=amount;i++){ dp[i]=INT_MAX; for(int j=0;j<len;j++){ if(coins[j]<=i && dp[i-coins[j]]!=INT_MAX){ dp[i]=min(dp[i-coins[j]]+1,dp[i]); } } } return dp[amount]==INT_MAX?-1:dp[amount]; } };
相关文章推荐
- C++动态规划之最长公子序列实例
- C++动态规划之背包问题解决方法
- C#使用动态规划解决0-1背包问题实例分析
- 动态规划
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- C++ 动态规划
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02