forked from jrpillai/RecursionInCombinations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
4-partition-number.js
61 lines (46 loc) · 1.03 KB
/
4-partition-number.js
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
/*
You are given a positive integer target.
Return an array of all arrays of ordered (ascending) positive integers that sum up to the target.
The arrays can be provided in any order.
Example:
partitionNumber(3) ->
[
[1, 1, 1],
[1, 2],
[3]
]
partitionNumber(4) ->
[
[1, 1, 1, 1],
[1, 1, 2],
[1, 3],
[2, 2],
[4]
]
The inner arrays must have ascending numbers, but can be provided in any order.
*/
function partitionNumber(num) {
const result = [];
const current = [];
// recursive function to generate results
(function generate(count = 1, target = num) {
// base cases
// found valid partition
if (target === 0) {
return result.push(current.slice());
}
// not valid path
if (target < count) {
return;
}
// take it
current.push(count);
generate(count, target - count);
//leave it
current.pop();
generate(count + 1, target);
})();
return result;
}
console.log(partitionNumber(3));
console.log(partitionNumber(4));