-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-097-createCombinations-2.js
72 lines (60 loc) · 2.19 KB
/
structy-097-createCombinations-2.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
62
63
64
65
66
67
68
69
70
71
72
// p: arr, num
// r: arr
// e:
// createCombinations(["a", "b", "c"], 2); // ->
// // [
// // [ 'a', 'b' ],
// // [ 'a', 'c' ],
// // [ 'b', 'c' ]
// // ]
const createCombinations = (arr, k) => {
if (arr.length === k) return [arr];
if (k === 0) return [[]];
const first = arr[0];
const aWOf = arr.slice(1);
const aLeft = createCombinations(aWOf, k - 1);
const aRight = createCombinations(aWOf, k);
for (let a of aLeft) {
a.push(first);
}
return [...aLeft, ...aRight];
};
// ["a", "b", "c", "d"] 3
// a / \
// [bc][bd][cd] ["b", "c", "d"] 2 ["b", "c", "d"] 3
// b / \ b / \
// [c][d] ["c", "d"] 1 ["c", "d"] 2 [c,d]2 [c,d]3
// c / \
// [] ["d"]0 ["d"]1
// d /
// []
// [[ab][ac][ad]-[bc][bd][cd]] ["a", "b", "c", "d"] 2
// a / \
// [[b]-[c][d] ] ["b", "c", "d"] 1 ["b", "c", "d"] 2 [[bc][bd]-[cd]]
// b / \ / \
// [[]-[c][d] ] ["c", "d"] 0 ["c", "d"] 1 ["c", "d"] 1 ["c", "d"] 2 [[c][d]]
// c / / \
// [d] [] [d] 0 [d] 1
// /
// []
// const createCombinations = (items, k) => {
// if (items.length < k) return [];
// if (k === 0) return [[]];
// const firstE = items[0];
// const itemsWOfirstE = items.slice(1);
// const left = createCombinations(itemsWOfirstE, k - 1);
// const right =
// itemsWOfirstE.length === k
// ? [itemsWOfirstE]
// : createCombinations(itemsWOfirstE, k);
// console.log(left, right);
// for (let l of left) {
// l.push(firstE);
// }
// return [...left, ...right];
// };
console.log(createCombinations(["a", "b", "c"], 3)); // ->)
// console.log(createCombinations([1, 28, 94], 3)); // ->
// [
// [ 1, 28, 94 ]
// ])