Leetcode Factor Combinations

来源:互联网 发布:怪物猎人帅哥捏脸数据 编辑:程序博客网 时间:2024/04/30 01:57

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


Difficulty: Medium


Easy Backtracking.


public class Solution {            public void helper(List<List<Integer>> res, List<Integer> temp, int target, int start){        double mid = Math.sqrt((double)(target));        if(target == 1){            res.add(new ArrayList<Integer>(temp));            return;        }        else{            temp.add(target);            res.add(new ArrayList<Integer>(temp));            temp.remove(temp.size() - 1);        }        for(int i = start; i <= mid;i++){            if(target%i == 0){                temp.add(i);                helper(res, temp, target/i, i);                temp.remove(temp.size() - 1);            }                    }    }        public List<List<Integer>> getFactors(int n) {        List<List<Integer>> res = new ArrayList<>();        List<Integer> temp = new ArrayList<Integer>();        double mid = Math.sqrt((double)(n));                for(int i = 2; i <= mid;i++){            if(n%i == 0){                temp.add(i);                helper(res, temp,n/i, i);                temp.remove(temp.size() - 1);            }        }        return res;            }}


0 0
原创粉丝点击