|
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 from a collections without considering the 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.current = [] // will be used for storing current combination |
29 | | - this.combinations = [] |
30 | | - } |
31 | | - |
32 | | - findCombinations(high = this.n, total = this.k, low = 1) { |
33 | | - if (total === 0) { |
34 | | - this.combinations.push([...this.current]) |
35 | | - return this.combinations |
| 1 | +function generateCombinations(n, k) { |
| 2 | + let currentCombination = [] |
| 3 | + let allCombinations = [] // will be used for storing all combinations |
| 4 | + let currentValue = 1 |
| 5 | + |
| 6 | + function findCombinations() { |
| 7 | + if (currentCombination.length === k) { |
| 8 | + // Add the array of size k to the allCombinations array |
| 9 | + allCombinations.push([...currentCombination]) |
| 10 | + return |
36 | 11 | } |
37 | | - for (let i = low; i <= high; i++) { |
38 | | - this.current.push(i) |
39 | | - this.findCombinations(high, total - 1, i + 1) |
40 | | - this.current.pop() |
| 12 | + if (currentValue > n) { |
| 13 | + // Check for exceeding the range |
| 14 | + return |
41 | 15 | } |
42 | | - return this.combinations |
| 16 | + currentCombination.push(currentValue++) |
| 17 | + findCombinations() |
| 18 | + currentCombination.pop() |
| 19 | + findCombinations() |
| 20 | + currentValue-- |
43 | 21 | } |
| 22 | + |
| 23 | + findCombinations() |
| 24 | + |
| 25 | + return allCombinations |
44 | 26 | } |
45 | 27 |
|
46 | | -export { Combinations } |
| 28 | +export { generateCombinations } |
0 commit comments