import java.util.ArrayList;
import java.util.List;
public 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
public static List<List<Integer>> partitions(int n) {
List<List<Integer>> results = new ArrayList<>();
backtrack(n, n, new ArrayList<>(), results);
return results;
}
/**
* Backtracking helper function.
*
* @param remaining how much is left to reach n
* @param max maximum allowed next number (keeps order non-increasing)
* @param current current partial partition
* @param results list of all partitions
*/
private static void backtrack(int remaining, int max, List<Integer> current, List<List<Integer>> results) {
// If nothing remains, we found a valid partition
if (remaining == 0) {
results.add(new ArrayList<>(current));
return;
}
// Try next numbers from max down to 1
for (int next = Math.min(remaining, max); next >= 1; next--) {
current.add(next); // choose
backtrack(remaining - next, next, current, results); // explore
current.remove(current.size() - 1); // un-choose (backtrack)
}
}
public static void main(String[] args) {
List<List<Integer>> result = partitions(5);
System.out.println(result);
}
}
/*
run:
[[5], [4, 1], [3, 2], [3, 1, 1], [2, 2, 1], [2, 1, 1, 1], [1, 1, 1, 1, 1]]
*/