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;
}
}