Skip to content

Commit 9e12e1c

Browse files
add: bracket combinations👌
1 parent 8d29ab1 commit 9e12e1c

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# 📓JavaScript Assessments
22

3+
- [Bracket Combinations](bracket-combinations)
34
- [Calculate the sum of the numbers in a nested array](calculate-the-sum-of-the-numbers-in-a-nested-array)
45
- [Convert string to group](convert-string-to-group)
56
- [Delete Overlapping Intervals](delete-overlapping-intervals)

bracket-combinations/README.md

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Bracket Combinations
2+
3+
Have the function `BracketCombinations(num)` read `num` which will be an integer greater than or equal to zero, and return the number of valid combinations that can be formed with num pairs of parentheses. For example, if the input is 3, then the possible combinations of 3 pairs of parenthesis, namely: `()()()`, are `()()()`, `()(())`, `(())()`, `((()))`, and `(()())`. There are 5 total combinations when the input is 3, so your program should return 5.
4+
5+
## Examples
6+
7+
```javascript
8+
BracketCombinations(2); // should == 2
9+
BracketCombinations(3); // should == 5
10+
```
11+
12+
## Execute
13+
14+
```bash
15+
node solution.js
16+
```

bracket-combinations/solution.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
function BracketCombinations(num) {
2+
if (num === 0) {
3+
return 1;
4+
}
5+
// By Doing sum search i found a formula that can achieve what this problem want
6+
// called Catalan number (Catalan Formula)
7+
// where catalan formula is ==> (2n!) / (n+1)! n!
8+
9+
// first i will calculate the factorial of the num
10+
let factorial = (n) => {
11+
let k = 1;
12+
for (var i = n; i >= 2; i--) {
13+
k *= i;
14+
}
15+
return k;
16+
};
17+
18+
// formula going down
19+
const result = factorial(2 * num) / (factorial(num + 1) * factorial(num));
20+
return result;
21+
}
22+
23+
(() => {
24+
[2, 3, 5, 8].forEach((num) => {
25+
console.log(JSON.stringify(num), '==', BracketCombinations(num));
26+
});
27+
})();

0 commit comments

Comments
 (0)