forked from jrpillai/RecursionInCombinations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
3-ht-permutations.js
58 lines (45 loc) · 1.11 KB
/
3-ht-permutations.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
/*
Let's say you flipped a coin multiple times, resulting in a given number of heads and tails. Return an array of strings
representing all possible histories given those numbers of heads and tails. The strings can be in any order.
Example:
htPermutations(2, 1) ->
[
'HHT',
'HTH'
'THH'
]
htPermutations(2, 2) ->
[
'HHTT',
'HTHT',
'HTTH',
'THHT',
'THTH',
'TTHH'
]
htPermutations(0, 3) ->
[
'TTT'
]
htPermutations(0, 0) ->
[
''
]
*/
function htPermutations(heads, tails) {
const result = [];
(function generate(str = '', m = heads, n = tails) {
// base case of running out of coins
if (m === 0 && n === 0) return result.push(str);
// take head
if (m > 0) generate(str + 'H', m - 1, n);
// take tail
if (n > 0) generate(str + 'T', m, n - 1);
// the leave it scenarios happen as the call stack pops off
})();
return result;
}
// Time complexity - O(2^(m+n)) - the decision tree has 2 branches at each node
console.log(htPermutations(2, 1));
console.log(htPermutations(2, 2));
console.log(htPermutations(0, 0));