An interesting DFS with a lot of details to take care of.
class Solution { vector<vector<int>> ret; void go(int n, vector<int> sofar, int minF) { int start = n % 2 ? 3 : 2; for (int f = start; f <= n / 2; f += 1) { if (f >= minF && n % f == 0 && (n / f) >= f) { vector<int> r = sofar; r.push_back(f); r.push_back(n/f); ret.push_back(r); r.pop_back(); go(n / f, r, f); } } } public: vector<vector<int>> getFactors(int n) { go(n, vector<int>(), 2); return ret; } };