Skip to content

feat(backtracking): all combinations of k numbers out of 1...n #148

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Aug 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions backtracking/all-combinations-of-size-k.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/**
* This generates an array of unique sub"sets" (represented by ascendingly sorted subarrays)
* of size k out of n+1 numbers from 1 to n.
*
* By using a backtracking algorithm we can incrementally build sub"sets" while dropping candidates
* that cannot contribute anymore to a valid solution.
* Steps:
* - From the starting number (i.e. "1") generate all combinations of k numbers.
* - Once we got all combinations for the given number we can discard it (“backtracks”)
* and repeat the same process for the next number.
*/
export function generateCombinations(n: number, k: number): number[][] {
let combinationsAcc: number[][] = [];
let currentCombination: number[] = [];

function generateAllCombos(
n: number,
k: number,
startCursor: number
): number[][] {
if (k === 0) {
if (currentCombination.length > 0) {
combinationsAcc.push(currentCombination.slice());
}
return combinationsAcc;
}

const endCursor = n - k + 2;
for (let i = startCursor; i < endCursor; i++) {
currentCombination.push(i);
generateAllCombos(n, k - 1, i + 1);
currentCombination.pop();
}
return combinationsAcc;
}

return generateAllCombos(n, k, 1);
}
26 changes: 26 additions & 0 deletions backtracking/test/all-combinations-of-size-k.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { generateCombinations } from "../all-combinations-of-size-k";

const cases = [
[
3,
2,
[
[1, 2],
[1, 3],
[2, 3],
],
],
[4, 2, [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]]],
[0, 0, []],
[2, 3, []],
] as const;

describe("AllCombinationsOfSizeK", () => {
it.each(cases)(
"create all combinations given n=%p and k=%p",
(n, k, expectedCombos) => {
const combinations = generateCombinations(n, k);
expect(combinations).toEqual(expectedCombos);
}
);
});