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