254. Factor Combinations

Description

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. You may assume that n is always positive.
  2. 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

注意不要出现重复解,传入一个start可以轻松解决,保证所有后续分解的因子都不小于start。

class Solution {
    public List> getFactors(int n) {
        List> factors = new ArrayList<>();
        getFactorsRecur(n, 2, new ArrayList<>(), factors);
        return factors;
    }
    
    public void getFactorsRecur(int n, int start, List factor
                                , List> factors) {
        if (n == 1) {
            if (factor.size() > 1) {    // important
               factors.add(new ArrayList<>(factor)); 
            }
            return;
        }

        for (int i = start; i <= n; ++i) {
            if (n % i != 0) {
                continue;
            }
            
            factor.add(i);
            getFactorsRecur(n / i, i, factor, factors);     // start with i!
            factor.remove(factor.size() - 1);
        }
    }
}

你可能感兴趣的:(254. Factor Combinations)