Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 7be5ce0

Browse files
chore: Merge pull request #748 from chiranjeev-thapliyal/master
added Backtracking/AllCombinationsOfSizeK
2 parents 2e6f8ae + 254f90b commit 7be5ce0

File tree

4 files changed

+12488
-10
lines changed

4 files changed

+12488
-10
lines changed

‎Backtracking/AllCombinationsOfSizeK.js

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
/*
2+
Problem: Given two numbers, n and k, make all unique combinations of k numbers from 1 to n and in sorted order
3+
4+
What is combinations?
5+
- Combinations is selecting items froms a collections without considering order of selection
6+
7+
Example:
8+
- We have an apple, a banana, and a jackfruit
9+
- We have three objects, and need to choose two items, then combinations will be
10+
11+
1. Apple & Banana
12+
2. Apple & Jackfruit
13+
3. Banana & Jackfruit
14+
15+
To read more about combinations, you can visit the following link:
16+
- https://betterexplained.com/articles/easy-permutations-and-combinations/
17+
18+
Solution:
19+
- We will be using backtracking to solve this questions
20+
- Take one element, and make all them combinations for k-1 elements
21+
- Once we get all combinations of that element, pop it and do same for next element
22+
*/
23+
24+
class Combinations {
25+
constructor (n, k) {
26+
this.n = n
27+
this.k = k
28+
this.combinationArray = [] // will be used for storing current combination
29+
}
30+
31+
findCombinations (high = this.n, total = this.k, low = 1) {
32+
if (total === 0) {
33+
console.log(this.combinationArray)
34+
return
35+
}
36+
for (let i = low; i <= high; i++) {
37+
this.combinationArray.push(i)
38+
this.findCombinations(high, total - 1, i + 1)
39+
this.combinationArray.pop()
40+
}
41+
}
42+
}
43+
44+
export { Combinations }
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
import { Combinations } from '../AllCombinationsOfSizeK'
2+
3+
describe('AllCombinationsOfSizeK', () => {
4+
it('should return 3x2 matrix solution for n = 3 and k = 2', () => {
5+
const test1 = new Combinations(3, 2)
6+
expect(test1.findCombinations).toEqual([[1, 2], [1, 3], [2, 3]])
7+
})
8+
9+
it('should return 6x2 matrix solution for n = 3 and k = 2', () => {
10+
const test2 = new Combinations(4, 2)
11+
expect(test2.findCombinations).toEqual([[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]])
12+
})
13+
})

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /