254. Factor Combinations

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.

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

总结见:http://www.jianshu.com/p/883fdda93a66

Solution:Backtracking

实现1a: regular
实现1b: i <= (int) Math.sqrt(n) instead of n, to speed up. some small changes required for corner cases.

Time Complexity: T(N) = T(N/2) + T(N/3) + T(N/4) + .. ? Space Complexity: O(N)

Solution1a Code:

class Solution {
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> cur_res = new ArrayList<>();
        
        getFactors(n, 2, cur_res, result);
        
        return result;
    }

    public void getFactors(int n, int start, List<Integer> cur_res, List<List<Integer>> result){
        if (n == 1 && cur_res.size() > 1) { // cur_res.size() > 1: to avoid the n itself to be the factor
            result.add(new ArrayList<Integer>(cur_res));
            return;
        }
        
        for (int i = start; i <= n; ++i) {
            if (n % i == 0) {
                cur_res.add(i);
                getFactors(n / i, i, cur_res, result);
                cur_res.remove(cur_res.size() - 1);
            }
        }
    }
}

Solution1b Code:

class Solution {
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> cur_res = new ArrayList<>();
        
        getFactors(n, 2, cur_res, result);
        
        return result;
    }

    public void getFactors(int n, int start, List<Integer> cur_res, List<List<Integer>> result){
        if (n == 1 ) {
            if(cur_res.size() > 1) { // cur_res.size() > 1: to avoid the n itself to be the factor
                result.add(new ArrayList<Integer>(cur_res));
            }
            
            return;
        }
            

        for (int i = start; i <= (int) Math.sqrt(n); ++i) { // ===> here, change 1
            if (n % i == 0) {
                cur_res.add(i);
                getFactors(n / i, i, cur_res, result);
                cur_res.remove(cur_res.size() - 1);
            }
        }
        
        int i = n; // ===> here, change 2, try to 处理 (int) Math.sqrt(n) 达不到原数的情况,如根2 = 1,则达不到2,这里corner case 加上
        cur_res.add(i);
        getFactors(n / i, i, cur_res, result);
        cur_res.remove(cur_res.size() - 1);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容