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:
coins = [1, 2, 5], amount = 11
return 3 (11 = 5 + 5 + 1)
Example 2:
coins = [2], amount = 3
return -1.
Note:
You may assume that you have an infinite number of each kind of coin.
解法1: 找规律 + Memorization, One pass O(N) Time
这题需要多写几个数出来找一下规律:
如果我们把0到15的二进制表达式写出来,并且把对应的set bit的个数写出来,我们可以得到如下:
0 0000 0
1 0001 1
2 0010 1
3 0011 2
4 0100 1
5 0101 2
6 0110 2
7 0111 3
8 1000 1
9 1001 2
10 1010 2
11 1011 3
12 1100 2
13 1101 3
14 1110 3
15 1111 4
观察后联系hint,发现偶数X的bit数是X/2的bit数,奇数X的bit数是X/2的bit数+1,于是可以得到一个O(N)的算法