-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcoin.js
More file actions
77 lines (73 loc) · 1.53 KB
/
Copy pathcoin.js
File metadata and controls
77 lines (73 loc) · 1.53 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* O(2^n)
* @param {*} nums
* @param {*} target
*/
function coinChangeRecursive(nums, target) {
const helper = (nums, target, n) => {
if (target === 0) {
return 1;
}
if (target < 0) {
return 0;
}
let key = `${nums[n]}-${target}`;
console.log(key);
let count = 0;
for (let i = n; i < nums.length; i++) {
count += helper(nums, target - nums[i], i);
}
return count;
};
return helper(nums, target, 0);
}
/**
* T: O(n * 2)
* @param {*} nums
* @param {*} target
*/
function coinChangeMemo(nums, target) {
let map = {};
const helper = (nums, target, n) => {
if (target === 0) {
return 1;
}
if (target < 0) {
return 0;
}
let key = `${nums[n]}-${target}`;
console.log(key);
if (key in map) {
console.log('****');
return map[key];
}
let count = 0;
for (let i = n; i < nums.length; i++) {
count += helper(nums, target - nums[i], i);
}
map[key] = count;
return map[key];
};
return helper(nums, target, 0);
}
/**
* T: O(n * target)
* @param {*} nums
* @param {*} target
*/
function coinChangeDP(nums, target) {
let dp = new Array(target + 1).fill(0);
dp[0] = 1;
for (let i = 0; i < nums.length; i++) {
let c = nums[i];
for (let j = 1; j < dp.length; j++) {
if (j >= c) {
dp[j] = dp[j] + dp[j - c];
}
}
}
return dp[target];
}
console.log(coinChangeRecursive([1, 2, 3], 4));
console.log(coinChangeMemo([1, 2, 3], 4));
console.log(coinChangeDP([1, 2, 3], 4));