注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号
x
https://leetcode.com/problems/factor-combinations/description/
follow up
允许负数的factor和要包含1的组合
以下是我的解法, 可是会有重复的情况,比如 32 的factor有
[1,2,2,2,2,-2]
[1,2,2,2,-2,2]
怎么去重比较好呢?
code:
- public static List<List<Integer>> getFactors(int n) {
- List<List<Integer>> result = new LinkedList<List<Integer>>();
- // if (n <= 3) {
- // return result;
- // }
- boolean odd = n < 0 ? true : false;
- List<Integer> list = new LinkedList<Integer>();
- list.add(1);
- helper(result, list, Math.abs(n), 2, 0, odd);
- return result;
- }
- private static void helper(List<List<Integer>> result, List<Integer> list, int n, int start, int negative, boolean odd) {
- if (n == 1) {
- if (list.size() >= 1) {
- if (odd && negative % 2 == 1 || !odd && negative % 2 == 0) {
- result.add(new LinkedList<Integer>(list));
- }
- }
- return;
- }
- for (int i = start; i <= n; i++) {
- if (n % i == 0) {
- // positive numbers
- list.add(i);
- helper(result, list, n / i, i, negative, odd);
- list.remove(list.size() - 1);
- //negative numbers
- list.add(-i);
- negative++;
- helper(result, list, n / i, i, negative, odd);
- negative--;
- list.remove(list.size() - 1);
- }
- }
- }
复制代码 |