leetcode254- Factor Combinations- medium

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]
]

  

算法:DFS。函数头:private void dfs(int target, int num, List<Integer> crt, List<List<Integer>> result) 

不断拆解为小一点的继续需要整除的数字。从num的数字开始,试着加入能被target整除的那些数字,来递归dfs(target / i, i, crt, result); 最后达到让target变成1的目标。

细节:用target % i == 0否来判断是否能够整除。

 
class Solution {
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<>();
        if (n <= 1) {
            return result;
        }
        dfs(n, 2, new ArrayList<Integer>(), result);
        return result;
    }
    
    private void dfs(int target, int num, List<Integer> crt, List<List<Integer>> result) {
        
        if (target == 1 && crt.size() > 1) {
            result.add(new ArrayList<Integer>(crt));
            return;
        }
        for (int i = num; i <= target; i++) {
            if (target % i != 0) {
                continue;
            }
            crt.add(i);
            dfs(target / i, i, crt, result);
            crt.remove(crt.size() - 1);
        }
    }
    
}

 

 

posted @ 2017-11-17 04:34  jasminemzy  阅读(121)  评论(0编辑  收藏  举报