[Leetcode] Factor Combinations 因数组合

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.

递归

复杂度

O(2^N) 时间 O(N) 空间

思路

递归,为了防止2,2,3和2,3,2这种重复,参数里需要一个start
递归函数接口定义:

helper函数找n的所有因式分解,每个因式分解最小的因子从start开始,后面的因子们升序排列,把所有这样的因式分解放到result里

void helper(int n,    //对谁进行因式分解
            int start,     //最小的因子有多大
            List<Integer> list,    //分解到n之前的因子们
            List<List<Integer>> result)    //结果

注意

输入的数不算做自己的因子
最开始的循环for(int i = start; i <= n; i++)非常费时,做了很多没用的事,可以这样:
for (int i = start; i <= sqrt(n); i++)这样省去了大量的无用计算,时间从228ms降到2ms,有100倍之多。
但是这样写会漏掉一种情况,就是n为因子的情况,加进去即可。

代码

public class Solution {
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> list = new ArrayList<>();
        helper(n, 2, list, result);
        return result;
    }
    public void helper(int n, int start, List<Integer> list, List<List<Integer>> result) {
        if (n == 1) {
            if (list.size() > 1) {  //the original input is not counted in
                result.add(new ArrayList<Integer>(list));
            }
            return;
        }
        for (int i = start; i <= Math.sqrt(n); i++) {   //这里只要到根号n就好了
            if (n % i == 0) {
                list.add(i);
                helper(n / i, i, list, result);
                list.remove(list.size() - 1);
            }
        }
        list.add(n);    //把n加进去
        helper(1, n, list, result);
        list.remove(list.size() - 1);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值