题目链接:https://leetcode.com/problems/factor-combinations/
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] ]
思路:DFS + backtracking。每次搜索从最小的一个因子开始到sqrt(n)查看之间的数是否可以被n整除,如果可以那么有两种选择:
1. n 除以这个因子,并保持这个因子, 然后进行下一层搜索。
2. 不再进行下一层搜索,保存当前结果。
其中 factor > sqrt(n) 是一个关键的剪枝, 保证了没有重复解.
代码如下:
class Solution {
public:
void DFS(int n, int factor, vector<int> vec)
{
if(factor > sqrt(n)) return;
DFS(n, factor+1, vec);
if(n%factor==0)
{
vec.push_back(factor);
DFS(n/factor, factor, vec);
vec.push_back(n/factor);
ans.push_back(vec);
}
}
vector<vector<int>> getFactors(int n) {
DFS(n, 2, vector<int>{});
return ans;
}
private:
vector<vector<int>> ans;
};