using System;
using System.Collections.Generic;
class IntegerPartitions
{
/*
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 ]
]
*/
// Function that returns all partitions of n
static List<List<int>> Partitions(int n)
{
var results = new List<List<int>>();
Backtrack(n, n, new List<int>(), results);
return results;
}
/*
Backtracking helper function.
remaining - how much is left to reach n
maxValue - maximum allowed next number (keeps order non-increasing)
current - current partial partition
results - list of all partitions
*/
static void Backtrack(int remaining, int maxValue, List<int> current, List<List<int>> results)
{
// If nothing remains, we found a valid partition
if (remaining == 0) {
results.Add(new List<int>(current));
return;
}
// Try next numbers from maxValue down to 1
for (int next = Math.Min(remaining, maxValue); next >= 1; next--) {
current.Add(next); // choose
Backtrack(remaining - next, next, current, results); // explore
current.RemoveAt(current.Count - 1); // un-choose (backtrack)
}
}
static void Main()
{
var result = Partitions(5);
Console.WriteLine("[");
for (int i = 0; i < result.Count; i++) {
Console.Write(" [ ");
for (int j = 0; j < result[i].Count; j++) {
Console.Write(result[i][j]);
if (j < result[i].Count - 1)
Console.Write(", ");
}
Console.Write(" ]");
if (i < result.Count - 1)
Console.WriteLine(",");
else
Console.WriteLine();
}
Console.WriteLine("]");
}
}
/*
run:
[
[ 5 ],
[ 4, 1 ],
[ 3, 2 ],
[ 3, 1, 1 ],
[ 2, 2, 1 ],
[ 2, 1, 1, 1 ],
[ 1, 1, 1, 1, 1 ]
]
*/