|
1 |
| -const frequency = (string, character) => { |
2 |
| - return string.split("").reduce((count, c) => { |
3 |
| - return count + (c == character ? 1 : 0); |
4 |
| - }, 0); |
5 |
| -}; |
6 |
| - |
7 |
| -const validParantheses = (N, store = "") => { |
8 |
| - const openBracketCount = frequency(store, "("); |
9 |
| - const closedBracketCount = frequency(store, ")"); |
10 |
| - |
| 1 | +const balancedParanthesis = (N, paranthesis = [], openCount, closedCount) => { |
11 | 2 | if (
|
12 |
| - openBracketCount > N || |
13 |
| - closedBracketCount > N || |
14 |
| - closedBracketCount > openBracketCount |
| 3 | + closedCount > openCount || |
| 4 | + paranthesis.length > 2 * N || |
| 5 | + openCount > N || |
| 6 | + closedCount > N |
15 | 7 | ) {
|
16 | 8 | return;
|
17 | 9 | }
|
18 |
| - |
19 |
| - if (store.length === 2 * N) { |
20 |
| - console.log(store); |
| 10 | + if (paranthesis.length === 2 * N) { |
| 11 | + console.log(paranthesis.join("")); |
21 | 12 | return;
|
22 |
| - } else { |
23 |
| - validParantheses(N, store + "("); |
24 |
| - validParantheses(N, store + ")"); |
25 | 13 | }
|
| 14 | + |
| 15 | + paranthesis = paranthesis.concat("("); |
| 16 | + balancedParanthesis(N, paranthesis, openCount + 1, closedCount); |
| 17 | + paranthesis = paranthesis.slice(0, paranthesis.length - 1); |
| 18 | + paranthesis = paranthesis.concat(")"); |
| 19 | + balancedParanthesis(N, paranthesis, openCount, closedCount + 1); |
26 | 20 | };
|
27 | 21 |
|
28 |
| -let count = 0, |
29 |
| - calls = 0; |
30 |
| -console.log(validParantheses(3, "")); |
31 |
| -console.log(count, calls); |
32 |
| -/* |
33 |
| -Parantheses Conditions |
34 |
| -1) Open < Count/2 |
35 |
| -2) Closed < Count/2 |
36 |
| -3) Open >= Closed |
37 |
| -4) Open === Closed return; |
38 |
| -*/ |
| 22 | +const N = 3; |
| 23 | +balancedParanthesis(N, [], 0, 0); |
| 24 | + |
0 commit comments