#include <iostream>
#include <vector>
/*
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
void backtrack(int remaining, int maxValue,
std::vector<int>& current,
std::vector<std::vector<int>>& results)
{
// If nothing remains, we found a valid partition
if (remaining == 0) {
results.push_back(current);
return;
}
// Try next numbers from maxValue down to 1
for (int next = std::min(remaining, maxValue); next >= 1; next--) {
current.push_back(next); // choose
backtrack(remaining - next, next, current, results); // explore
current.pop_back(); // un-choose (backtrack)
}
}
// Function that returns all partitions of n
std::vector<std::vector<int>> partitions(int n) {
std::vector<std::vector<int>> results;
std::vector<int> current;
backtrack(n, n, current, results);
return results;
}
int main() {
std::vector<std::vector<int>> result = partitions(5);
std::cout << "[" << std::endl;
for (size_t i = 0; i < result.size(); i++) {
std::cout << " [ ";
for (size_t j = 0; j < result[i].size(); j++) {
std::cout << result[i][j];
if (j < result[i].size() - 1)
std::cout << ", ";
}
std::cout << " ]";
if (i < result.size() - 1)
std::cout << "," << std::endl;
else
std::cout << std::endl;
}
std::cout << "]" << std::endl;
}
/*
run:
[
[ 5 ],
[ 4, 1 ],
[ 3, 2 ],
[ 3, 1, 1 ],
[ 2, 2, 1 ],
[ 2, 1, 1, 1 ],
[ 1, 1, 1, 1, 1 ]
]
*/