|
1 | 1 | class Solution: |
2 | | - def countQuadruplets(self, nums): |
3 | | - # Runtime-Memory trade-off using hash table |
4 | | - # a + b + c = d means a + b = d - c, so |
5 | | - # we store all d - c values in a hash table, then check for each a + b |
6 | | - abstract = dict() |
7 | | - ans = 0 |
8 | | - for c in range(2, len(nums) - 1): # Due to a < b < c < d |
9 | | - for d in range(c + 1, len(nums)): |
10 | | - minus = nums[d] - nums[c] |
11 | | - if minus not in abstract: |
12 | | - abstract[minus] = [[c, d]] |
13 | | - else: |
14 | | - abstract[minus].append([c, d]) |
| 2 | + def change(self, amount, coins): |
| 3 | + coins = sorted(coins) |
| 4 | + coins.insert(0, 0) |
| 5 | + coin_num = len(coins) |
| 6 | + array = [[0 for i in range(coin_num)] for j in range(amount + 1)] |
| 7 | + # array[b][c] means the number of combination that sum = b, |
| 8 | + # in the case we only use first c coins |
| 9 | + # Base case with c = 1 |
| 10 | + array[0] = [1] * coin_num |
| 11 | + for b in range(0, amount + 1): |
| 12 | + # If coins[1] divided by b, then we have 1 combination |
| 13 | + # that contain b/coins[1] element, else we do not have |
| 14 | + # any combination |
| 15 | + if b % coins[1] == 0: |
| 16 | + array[b][1] = 1 |
| 17 | + # else array[b][1] = 0, but we initialize with 0, so we do nothing |
15 | 18 |
|
16 | | - # Then check for each sum a + b |
17 | | - for a in range(len(nums) - 3): |
18 | | - for b in range(a + 1, len(nums) - 2): |
19 | | - current_sum = nums[a] + nums[b] |
20 | | - if current_sum not in abstract: |
21 | | - # Can not find any (a,b,c,d) satisfy |
22 | | - continue |
| 19 | + for c in range(2, len(coins)): |
| 20 | + # c is the number of coin we use |
| 21 | + c_amount = coins[c] |
| 22 | + for b in range(1, amount + 1): |
| 23 | + # The case we use maximun max_num c-th coins |
| 24 | + max_num = int(b / c_amount) |
| 25 | + # Each element in part is the case we use exactly i c-th coins |
| 26 | + part = [array[b - i * c_amount][c - 1] for i in range(max_num + 1)] |
| 27 | + array[b][c] += sum(part) |
23 | 28 |
|
24 | | - for element in abstract[current_sum]: |
25 | | - if element[0] > b: # Due to b < c |
26 | | - ans += 1 |
27 | | - return ans |
| 29 | + return array[amount][coin_num - 1] |
28 | 30 |
|
29 | 31 |
|
30 | 32 | obj = Solution() |
31 | | - |
32 | | -arr = [3, 3, 6, 4, 5] |
33 | | -print(obj.countQuadruplets(arr)) |
| 33 | +amount = 5 |
| 34 | +coins = [1, 2, 5] |
| 35 | +ans = obj.change(amount, coins) |
| 36 | +print(ans) |
0 commit comments