便宜上、この投稿のBLUEPIXYの回答を少し編集しました。
#include <iostream>
#include <vector>
void save(std::vector<std::vector<int> > & dest, std::vector<int> const & v, int level){
dest.push_back(std::vector<int>(v.begin(), v.begin() + level + 1));
}
void partition(int n, std::vector<int> & v, std::vector<std::vector<int> > & dest, int level = 0){
int first; /* first is before last */
if(0 == n){
return;
}
v[level] = n;
save(dest, v, level);
first = (level == 0) ? 1 : v[level - 1];
for(int i = first; i <= (n / 2); ++i){
v[level] = i; /* replace last */
partition(n - i, v, dest, level + 1);
}
}
int main(int argc, char ** argv) {
int N = 30;
std::vector<int> vec(N);
std::vector<std::vector<int> > partitions;
// You could change N * N to minimize the number of relocations
partitions.reserve(N * N);
partition(N, vec, partitions);
std::cout << "Partitions: " << partitions.size() << std::endl;
for(std::vector<std::vector<int> >::iterator pit = partitions.begin(); pit != partitions.end(); ++pit) {
std::cout << '[';
for(std::vector<int>::iterator it = (*pit).begin(); it != (*pit).end(); ++it) {
std::cout << *it << '\t';
}
std::cout << ']' << std::endl;
}
return 0;
}
ideoneでの出力