322. Coin Change

  • 26.2%

https://leetcode.com/problems/coin-change/#/description

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.

1
2
3
Example 1:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
1
2
3
Example 2:
coins = [2], amount = 3
return -1.

Note:

You may assume that you have an infinite number of each kind of coin.


方法一:

动态规划

152ms, 44.44%, 180 / 180, April.27th, 2016

https://leetcode.com/discuss/76194/c-o-n-amount-time-o-amount-space-dp-solution

[C++] O(n * amount) time O(amount) space DP solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int Max = amount + 1;
vector<int> dp(amount + 1, Max);
dp[0] = 0;
for(int i = 1; i <= amount; i++){
for(int j = 0; j < coins.size(); j++)
if(coins[j] <= i)
dp[i] = min(dp[i], dp[i - coins[j]] + 1);
}
return dp[amount] > amount ? -1 : dp[amount];
}
};

我的代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
if(amount<=0) return 0;
int n = coins.size();
if(n==0) return -1;
vector<int> dp(amount+1, INT_MAX);
dp[0] = 0;
for(int i=0; i<=amount; i++){
for(int j=0; j<n; j++)
// 要判断前面的是否为INT_MAX
if(coins[j]<=i && dp[i-coins[j]]!=INT_MAX)
dp[i] = min(dp[i], dp[i-coins[j]]+1);
}
// 此处需要判断一下,不能直接返回dp[amount]
return dp[amount]==INT_MAX ? -1 : dp[amount];
}
};

方法二:

类似于方法一,dp算法,vector中保存的都是-1

其他思路相同,好处是返回值,直接返回了结果

https://discuss.leetcode.com/topic/32602/c-dp-solution-o-n-m-time-o-m-space

C++ dp solution, O(N * M) time, O(M) space

dp[i] means the solution of amount ‘i’. Initialise each element of the dp array to -1, then for each coin value c:

1). if i - c < 0, do nothing.

2). if i - c >= 0 and dp[i - c] != -1, means there is a solution of amount ‘i - c’, dp[i] = min(dp[i], dp[i - c] + 1)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution
{
public:
int coinChange(vector<int>& coins, int amount)
{
vector<int> dp(amount + 1, -1);
dp[0] = 0;

for (int i = 1; i <= amount; ++i)
for (auto & c : coins)
if (i - c >= 0 && dp[i - c] != -1)
dp[i] = dp[i] > 0 ? min(dp[i], dp[i - c] + 1) : dp[i - c] + 1;

return dp[amount];
}
};

https://discuss.leetcode.com/topic/32589/fast-python-bfs-solution

Fast Python BFS Solution

This solution is inspired by the BFS solution for problem Perfect Square. Since it is to find the least coin solution (like a shortest path from 0 to amount), using BFS gives results much faster than DP.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
if amount == 0:
return 0
value1 = [0]
value2 = []
nc = 0
visited = [False]*(amount+1)
visited[0] = True
while value1:
nc += 1
for v in value1:
for coin in coins:
newval = v + coin
if newval == amount:
return nc
elif newval > amount:
continue
elif not visited[newval]:
visited[newval] = True
value2.append(newval)
value1, value2 = value2, []
return -1

https://discuss.leetcode.com/topic/32743/clean-dp-python-code

Clean dp python code

Assume dp[i] is the fewest number of coins making up amount i, then for every coin in coins, dp[i] = min(dp[i - coin] + 1).

The time complexity is O(amount * coins.length) and the space complexity is O(amount)

1
2
3
4
5
6
7
8
9
class Solution(object):
def coinChange(self, coins, amount):
MAX = float('inf')
dp = [0] + [MAX] * amount

for i in xrange(1, amount + 1):
dp[i] = min([dp[i - c] if i - c >= 0 else MAX for c in coins]) + 1

return [dp[amount], -1][dp[amount] == MAX]

https://discuss.leetcode.com/topic/33840/fast-python-branch-and-bound-solution-beaten-99-python-submissions

Fast python branch and bound solution, beaten 99% python submissions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
def coinChange(self, coins, amount):
if len(coins) == 0:
return -1
if amount == 0:
return 0

# try biggest coins first
sortedCoins = sorted(coins, reverse=True)

# upper bound on number of coins (+1 to represent the impossible case)
upperBound = (amount + sortedCoins[-1] - 1) / sortedCoins[-1] + 1

self.bestNCoins = upperBound

self.branchAndBoundSearch(sortedCoins, amount, 0)

if self.bestNCoins == upperBound:
return -1
else:
return self.bestNCoins

def branchAndBoundSearch(self, sortedCoins, amount, nCoins):
# lower bound on number of coins, achieved using the biggest coin
lowerBound = nCoins + (amount + sortedCoins[0] - 1) / sortedCoins[0]

if lowerBound > self.bestNCoins:
return

if len(sortedCoins) == 0:
return

# if amount matches the biggest coin, that is the solution
if amount == sortedCoins[0] and nCoins + 1 < self.bestNCoins:
self.bestNCoins = nCoins + 1
return

# try use the biggest coin
if amount > sortedCoins[0]:
self.branchAndBoundSearch(sortedCoins, amount - sortedCoins[0], nCoins + 1)

# else try not to use the biggest coin
if len(sortedCoins) > 1:
self.branchAndBoundSearch(sortedCoins[1:], amount, nCoins)

308ms, 93.13%, 180 / 180, April.28th, 2016

https://leetcode.com/discuss/76737/clean-dp-python-code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
class Solution(object):
def coinChange(self, coins, amount):
if len(coins) == 0:
return -1
if amount == 0:
return 0

# try biggest coins first
sortedCoins = sorted(coins, reverse=True)

# upper bound on number of coins (+1 to represent the impossible case)
upperBound = (amount + sortedCoins[-1] - 1) / sortedCoins[-1] + 1

self.bestNCoins = upperBound

self.branchAndBoundSearch(sortedCoins, amount, 0)

if self.bestNCoins == upperBound:
return -1
else:
return self.bestNCoins

def branchAndBoundSearch(self, sortedCoins, amount, nCoins):
# lower bound on number of coins, achieved using the biggest coin
lowerBound = nCoins + (amount + sortedCoins[0] - 1) / sortedCoins[0]

if lowerBound > self.bestNCoins:
return

if len(sortedCoins) == 0:
return

# if amount matches the biggest coin, that is the solution
if amount == sortedCoins[0] and nCoins + 1 < self.bestNCoins:
self.bestNCoins = nCoins + 1
return

# try use the biggest coin
if amount > sortedCoins[0]:
self.branchAndBoundSearch(sortedCoins, amount - sortedCoins[0], nCoins + 1)

# else try not to use the biggest coin
if len(sortedCoins) > 1:
self.branchAndBoundSearch(sortedCoins[1:], amount, nCoins)

solution 2:

1180ms, 180 / 180, April.28th, 2016

https://leetcode.com/discuss/76737/clean-dp-python-code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def coinChange(self, coins, amount):
"""
:type coins: List[int]
:type amount: int
:rtype: int
"""
MAX = float('inf')
dp = [0] + [MAX] * amount

for i in xrange(1, amount + 1):
dp[i] = min([dp[i-c] + 1 if i - c >= 0 else MAX for c in coins])

return dp[amount] if dp[amount] != MAX else -1
谢谢你,可爱的朋友。