#include <stdio.h>
/*
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 ]
]
*/
/*
Backtracking helper function.
remaining - how much is left to reach n
maxValue - maximum allowed next number (keeps order non-increasing)
current[] - current partial partition
index - current length of the partition
*/
void backtrack(int remaining, int maxValue, int current[], int index) {
// If nothing remains, we found a valid partition
if (remaining == 0) {
printf(" [ ");
for (int i = 0; i < index; i++) {
printf("%d", current[i]);
if (i < index - 1)
printf(", ");
}
printf(" ]\n");
return;
}
// Try next numbers from maxValue down to 1
for (int next = (remaining < maxValue ? remaining : maxValue); next >= 1; next--) {
current[index] = next; // choose
backtrack(remaining - next, next, current, index + 1); // explore
}
}
/*
Function that prints all partitions of n
*/
void partitions(int n) {
int current[100]; // enough for any reasonable partition
backtrack(n, n, current, 0);
}
int main() {
printf("[\n");
partitions(5);
printf("]\n");
return 0;
}
/*
run:
[
[ 5 ]
[ 4, 1 ]
[ 3, 2 ]
[ 3, 1, 1 ]
[ 2, 2, 1 ]
[ 2, 1, 1, 1 ]
[ 1, 1, 1, 1, 1 ]
]
*/