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依次对每个因子试除,如果余数为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;
    }
};
    原文作者:楷书
    原文地址: https://www.jianshu.com/p/0cc6aeb68a87
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞