Almost the same idea as combinations (permutations)
#include <vector>
#include <iostream>
using namespace std;
/*
Numbers can be regarded as product of its factor. For example.
8 = 2 x 2 x 2
= 2 x 4
write a function that takes an integer n and return all possible combinations
of its factor.
Note:
1: Each combination's factors must be sorted ascending, for example
The factors of 2 and 6 is [2, 6], not [6, 2]
2: You may assume that n is always positive.
3: Factors should be greater than 1 and less than n.
Example:
Input: 37, Output: []
Input: 12, Output: [[2, 6], [2, 2, 3], [3, 4]]
*/
void getFactors(int n, vector<int>& path, vector< vector<int> >& res, int start) {
if(n == 1 && path.size() > 1) {
res.push_back(path);
return;
}
for(int i = start; i <= n; ++i) {
if(n % i == 0) {
path.push_back(i);
getFactors(n / i, path, res, i);
path.pop_back();
}
}
}
vector< vector<int> > getFactors(int n) {
if(n <= 1) return {};
vector<int> path;
vector< vector<int> > res;
getFactors(n, path, res, 2);
return res;
}
int main(void) {
vector< vector<int> > res = getFactors(8);
for(int i = 0; i < res.size(); ++i) {
for(int j = 0; j < res[i].size(); ++j) {
cout << res[i][j] << " ";
}
cout << endl;
}
}