- Factorization
中文English
A non-negative numbers can be regarded as product of its factors.
Write a function that takes an integer n and return all possible combinations of its factors.
Example
Example1
Input: 8
Output: [[2,2,2],[2,4]]
Explanation:
8 = 2 x 2 x 2 = 2 x 4
Example2
Input: 1
Output: []
Notice
Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
The solution set must not contain duplicate combination.
解法1:DFS搜索。
思路:这题与subset有点相似,
注意:
- 在helper里面,要判断v.size()>0,不然就会把空集加进去。
- for()里面,上限是sqrt(n)。
- helper()里面,if()里面push_back(v)之后,千万不能返回,这里跟subset不一样。
- 不需要sort。
举例如下:
input = 12。
一开始i = 2, 将2存入v,递归后helper(6, 2, v, vv),将{2,6}存入vv,v弹出6。继续for循环,将另一个2存入v,递归helper(3, 2, v, vv),将{2,2,3}存入vv,弹出3。后面以2开始的for循环再不满足条件了。将2逐个从v中弹出。
i=3的时候,将3存入v,递归后helper(4,3,v,vv),将{3,4}存入vv, v弹出4。继续for循环,后面都不满足条件了。
所以返回{{2,6}, {2,2,3}, {3, 4}}。
注意这里helper()里面if()里千万不能返回。这样,6还可以继续处理成{2,3}。
代码如下:
class Solution {
public:
/**
* @param n: An integer
* @return: a list of combination
*/
vector<vector<int>> getFactors(int n) {
vector<int> v;
vector<vector<int>> vv;
helper(n, 2, v, vv);
return vv;
}
private:
void helper(int n, int index, vector<int> & v, vector<vector<int>> &vv) {
if (v.size() > 0) {
v.push_back(n);
vv.push_back(v);
v.pop_back();
}
for (int i = index; i <= sqrt(n); ++i) {
if (n % i == 0) {
v.push_back(i);
helper(n / i, i, v, vv);
v.pop_back();
}
}
}
};