254. Factor Combinations

怎么今天全是BACKTRACK的题。

这个也一样,剪枝就行了,算因数的时候一开始是觉得不能超过一半,但是12会出现34 43这样的情况,进而想起不能超过平方根。。

然后每次分解的因子,再分解的时候不能小于上一个因子,否则就又有重复。

最后,没了。

public class Solution 
{

    
    public List<List<Integer>> getFactors(int n) 
    {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        if(n <= 1) return res;
        
        helper(res,n,new ArrayList<Integer>(),2);
        
        return res;
    }
    
    public void helper(List<List<Integer>> res, int n, List<Integer> tempList,int m)
    {
        if(n <= 1) return;
        for(int i = m; i*i <= n; i++)
        {
            if(n%i == 0 && n/i >= m)
            {
                tempList.add(i);
                tempList.add(n/i);
                res.add(new ArrayList<Integer>(tempList));
                tempList.remove(tempList.size()-1);
                helper(res,n/i,new ArrayList<>(tempList),i);
                tempList.remove(tempList.size()-1);
            }
        }
    }
}
posted @ 2016-10-14 08:19  哇呀呀..生气啦~  阅读(62)  评论(0编辑  收藏  举报