Let n = x_1 + x_2 + ... + x_k be a partition of the number into natural summands. According to the problem statement, the summands in any partition must satisfy the inequality:
The first summand x_1 can take values from to , and each subsequent x_i~(2 \le i \le k) can take values from to x_{i-1}.
The recursive idea behind the partition generation procedure is as follows: if, when partitioning the number , the first summand x_1~(x_1 \le n) is chosen, then one should recursively generate all possible partitions of the number n - x_1 into summands that do not exceed x_1.
Algorithm implementation
We'll use the array to generate the partitions of the number .
int x[50];The function f generates the partitions of the number and takes three arguments:
— the current position in the array ;
— the maximum allowed value of the summand that can be placed at position ;
— the current value of the number to be partitioned.
void f(int pos, int max, int n)
{If the value of becomes zero, it means the partition is complete, and the current contents of the array represent one of the partitions. In this case, we print the array.
if (n == 0)
{
for (int i = 0; i < pos; i++)
printf("%d ", x[i]);
printf("\n");
return;
}At position of the array , any number from to min(max, n) can be placed.
for (int i = 1; i <= min(max, n); i++)
{
x[pos] = i;
f(pos + 1, i, n - i);
}
}The main part of the program. Read the input value and start the function to generate all possible partitions of this number.
scanf("%d",&n);
f(0,n,n);