8000 Update AllCombinationsOfSizeK.js · imrahulkb/JavaScript@f4d6fed · GitHub
[go: up one dir, main page]

Skip to content

Commit f4d6fed

Browse files
authored
Update AllCombinationsOfSizeK.js
1 parent fd4b48c commit f4d6fed

File tree

1 file changed

+24
-22
lines changed

1 file changed

+24
-22
lines changed

Backtracking/AllCombinationsOfSizeK.js

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -21,29 +21,31 @@
2121
- Once we get all combinations of that element, pop it and do same for next element
2222
*/
2323

24-
class Combinations {
25-
constructor(n, k) {
26-
this.n = n
27-
this.k = k
28-
this.current = [] // will be used for storing current combination
29-
this.combinations = []
30-
this.i = 1
24+
function generateCombinations(n, k) {
25+
let currentCombination = []
26+
let allCombinations = [] // will be used for storing all combinations
27+
let currentValue = 1
28+
29+
function findCombinations() {
30+
if (currentCombination.length === k) {
31+
// Add the array of size k to the allCombinations array
32+
allCombinations.push([...currentCombination])
33+
return
34+
}
35+
if (currentValue > n) {
36+
// Check for exceeding the range
37+
return
38+
}
39+
currentCombination.push(currentValue++)
40+
findCombinations()
41+
currentCombination.pop()
42+
findCombinations()
43+
currentValue--
3144
}
3245

33-
findCombinations() {
34-
if (this.current.length == this.k) { //will add the array of size k to combinations array
35-
this.combinations.push([...this.current])
36-
return
37-
}
38-
if (this.i > this.n) //check for exceeding range
39-
return
40-
this.current.push(this.i++)
41-
this.findCombinations()
42-
this.current.pop()
43-
this.findCombinations()
44-
this.i--
45-
return this.combinations
46-
}
46+
findCombinations()
47+
48+
return allCombinations
4749
}
4850

49-
export { Combinations }
51+
export { generateCombinations }

0 commit comments

Comments
 (0)
0