You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
Example 2:
Note:
You may assume that you have an infinite number of each kind of coin.
dp一维数组每个元素代表达到金钱i所需要的最少硬币数,根据之前空间的数据递归求解。
我自己写了一个用二维数组的dp解法,行i代表硬币下标,列j代表总钱数,元素代表在用了coins[i]之前的硬币所能达到j的最少货币数,然而有个corn case,-1与0如何区分?所以并没有accepted,以后可以完善下。
然而创建二维dp数组的做法不建议,因为硬币可以任意选任何一个,dp[i][j] = Math.min(dp[i - 1][j - k * coins[i]] + k, dp[i][j])无法成立。
类似的题目可以在《程序员代码面试指南》找到。
这种硬币系列分为两种:①最少货币数(Min Path);②多少种方法(Distinct way)。
这两种都是可以用一维dp数组来做。
参考资料:
The text was updated successfully, but these errors were encountered: