/**
* Generate all ways to write a positive integer n
* as a sum of positive integers (integer partitions).
*
* Example: partitions(4) returns:
* [
* [4],
* [3,1],
* [2,2],
* [2,1,1],
* [1,1,1,1]
* ]
*/
export function partitions(n: number): number[][] {
const results: number[][] = [];
/**
* Backtracking helper
* @param remaining - how much is left to sum to
* @param max - largest allowed next number (to keep order non‑increasing)
* @param current - current partial partition
*/
function backtrack(remaining: number, max: number, current: number[]) {
// If nothing remains, we found a valid partition
if (remaining === 0) {
results.push([...current]);
return;
}
// Try all next numbers from min(remaining, max) down to 1
for (let next = Math.min(remaining, max); next >= 1; next--) {
current.push(next);
backtrack(remaining - next, next, current);
current.pop(); // backtrack
}
}
backtrack(n, n, []);
return results;
}
console.log(partitions(5));
/*
run:
[
[ 5 ],
[ 4, 1 ],
[ 3, 2 ],
[ 3, 1, 1 ],
[ 2, 2, 1 ],
[ 2, 1, 1, 1 ],
[ 1, 1, 1, 1, 1 ]
]
*/