254. Factor Combinations

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: **

  1. Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
  2. You may assume that n is always positive.
  3. 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依次對每個因子試除,如果余數(shù)為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;
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容