Problem
Numbers can be regarded as product of its factors. 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 factors.
**Note: **
- Each combination’s factors must be sorted ascending, for example: The factors of 2 and 6 is
[2, 6]
, not[6, 2]
. - You may assume that n is always positive.
- Factors should be greater than 1 and less than n.
Examples:
input: 1
output:
[]
input: 37
output:
[]
input: 12
output:
[
[2, 6],
[2, 2, 3],
[3, 4]
]
input: 32
output:
[
[2, 16],
[2, 2, 8],
[2, 2, 2, 4],
[2, 2, 2, 2, 2],
[2, 4, 4],
[4, 8]
]
Solution
DFS的思想。想枚举出所有的factors,然后dfs依次对每个因子试除,如果余数为0,则可视为一个结果。并把它放入最终结果。这里要注意如果 d = n / factors,并且 d >= factors,才把它放入结果,首先保证了sorted,另外如果d < factors,说明之前肯定有 factors’ = d 的情况已经做过了,没有必要再做一次。
class Solution {
private:
vector<int> factors;
public:
void solve(int dep, int maxDep, int n, vector<int> &ans, vector<vector<int>> &ret) {
for(int i = dep; i < maxDep; i++) {
int mod = n % factors[i];
if (mod == 0) {
int d = n / factors[i];
ans.push_back(factors[i]);
if (d >= factors[i]) {
vector<int> a(ans);
a.push_back(d);
ret.push_back(a);
if (d > factors[i]) {
solve(i, maxDep, d, ans, ret);
}
}
ans.pop_back();
}
}
}
vector<vector<int>> getFactors(int n) {
for(int i = 2; i < n; i++) {
if (n % i == 0) {
factors.push_back(i);
}
}
vector<vector<int>> ret;
vector<int> ans;
if (factors.size() != 0) {
solve(0, factors.size(), n, ans, ret);
}
return ret;
}
};