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:
You may assume that n is always positive.
Factors should be greater than 1 and less than n.
Example 1:
Input: 1
Output: []
Example 2:
Input: 37
Output:[]
Example 3:
Input: 12
Output:
[
[2, 6],
[2, 2, 3],
[3, 4]
]
Example 4:
Input: 32
Output:
[
[2, 16],
[2, 2, 8],
[2, 2, 2, 4],
[2, 2, 2, 2, 2],
[2, 4, 4],
[4, 8]
]
我的答案:
本以為很簡單的一道題,沒想到竟然有這么兩個巨坑,不虧是M
- 坑1:for循環(huán)里面的結(jié)尾判斷是<還是<=
- 我一開始想當(dāng)然覺得是<,因為從2開始,那么不可能搜索到n/2了,結(jié)果就被4打臉了,所以必須是<=,但這樣就造成后面很多問題了
- 坑2:如何去重?
- 無腦篩選是會重復(fù)的,所以必須有個start的數(shù)字,for循環(huán)里面每個i,都不可能再新加一個<i的元素
- 所以要screen out掉2,但是2<=2<=2,所以得在for里面的if也判斷一次,必須讓n/i這個可能新加入的元素也要>=i
class Solution {
public:
vector<vector<int>> getFactors(int n, int start=2) {
vector<vector<int>> ans;
for (int i=start; i<=n/start; ++i) {
// cout << n << " " << i << " " << n%i << endl;
if (n%i == 0 and n/i>=i) {
ans.push_back({n/i, i});
for (auto& sub_factor:getFactors(n/i, i)) {
sub_factor.push_back(i);
ans.push_back(sub_factor);
}
}
}
return ans;
}
};
Runtime: 92 ms, faster than 39.83% of C++ online submissions for Factor Combinations.
Memory Usage: 7.4 MB, less than 17.80% of C++ online submissions for Factor Combinations.
稍微優(yōu)化了一下代碼,用一個reference叫temp的vector<int>表示已經(jīng)搜索過的
class Solution {
private:
vector<vector<int>> ans;
public:
vector<vector<int>> getFactors(int n) {
vector<int> temp;
helper(n, temp, 2);
return ans;
}
void helper(int n, vector<int>& temp, int start) {
for (int i=start; i<=n/start; ++i) {
if (n%i == 0 and n/i >= i) {
temp.insert(temp.end(), {i,n/i});
ans.push_back(temp);
temp.pop_back();
helper(n/i, temp, i);
temp.pop_back();
}
}
}
};
Runtime: 60 ms, faster than 44.49% of C++ online submissions for Factor Combinations.
Memory Usage: 7 MB, less than 76.27% of C++ online submissions for Factor Combinations.

如何成為0ms?
- 把i<=n/i放到for循環(huán)的結(jié)束判斷里
class Solution {
private:
vector<vector<int>> ans;
public:
vector<vector<int>> getFactors(int n) {
vector<int> temp;
helper(n, temp, 2);
return ans;
}
void helper(int n, vector<int>& temp, int start) {
for (int i=start; i<=min(n/start,n/i); ++i) {
if (n%i == 0) {
temp.insert(temp.end(), {i,n/i});
ans.push_back(temp);
temp.pop_back();
helper(n/i, temp, i);
temp.pop_back();
}
}
}
};