Leetcode - Factor Combination

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:
Each combination's factors must be sorted ascending, for example: The factors of 2 and 6 is [2, 6], not [6, 2].
You may assume that n is always positive.
Factors should be greater than 1 and less than n.

[分析]
依次判断2到n的平方根是否能被n整除,如果可以整除则当前 i 和 n / i是一个可行解,然后递归获取 n / i的所有因子组合,它们将与 i 一起组合成 n 的因子组合。
为避免得到重复解并满足因子组合各项从小到大排列,有两个注意点:
1)如果 i * i > n / i,无需递归,因为 n / i分解所得因子必然小于i,不符合要求。
2)递归 n / i时最小因子要从 i开始


public class Solution {
public List<List<Integer>> getFactors(int n) {
return getFactorsWithStartParam(n, 2);
}
public List<List<Integer>> getFactorsWithStartParam(int n, int start) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (n < 4) return ret;
int sqrt = (int)Math.sqrt(n);
for (int i = start; i <= sqrt; i++) {
if (n % i == 0) {
int factor2 = n / i;
List<Integer> item = new ArrayList<Integer>();
item.add(i);
item.add(factor2);
ret.add(item);
if (i * i <= factor2) {// avoid get smaller factor than i
for (List<Integer> subitem : getFactorsWithStartParam(factor2, i)) {// avoid get smaller factor than i
subitem.add(0, i);
ret.add(subitem);
}
}
}
}
return ret;
}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值