[LinkedIn]Combination factors

From Here

Linkedin 的一道题目

Keep track of the current remain factor to be decomposed, LargestFactor is the largest possible factor to decompose (so that we don’t need to try anything larger than that).

For each level we try to decompose the current remaining factor.

import java.util.*;
public class Test {
    public List<List<Integer>> factorCombinations(int n) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        //change largestFactor to n to start from itself
        helper(ans, n, n/2, new ArrayList<Integer>());
        return ans;
    }
    private void helper(List<List<Integer>> ans, int num, int largestFactor, List<Integer> path) {
        if (num == 1) {
            ans.add(new ArrayList<Integer>(path));
            return;
        }
        for (int i = largestFactor; i > 1; i--) {
            if (num % i == 0) {
                path.add(i);
                helper(ans, num / i, i, path);
                path.remove(path.size() - 1);
            }
        }
    }
    public static void main(String[] args) {
        Test t = new Test();
        List<List<Integer>> l = t.factorCombinations(24);
        for (List<Integer> li : l) {
            for (Integer i : li) {
                System.out.print(i+" ");
            }
            System.out.println();
        }
    }
}

a more clear way to do it using , credit to Jiasen Lin~

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class Factors {
    public List<List<Integer>> factorCombinations(int n) {
        List<List<Integer>> ans = new ArrayList<List<Integer>>();
        // change largestFactor to n to start from itself
        Stack<Integer> stack = new Stack<Integer>();
        helper(ans, n, n, stack);
        return ans;
    }

    private void helper(List<List<Integer>> ans, int num, int largestFactor, Stack<Integer> stack) {
        if (num == 1) {
            List<Integer> list = new ArrayList<Integer>();
            for (int i : stack) {
                list.add(i);
            }
            ans.add(list);
            return;
        }
        for (int i = largestFactor; i > 1; i--) {
            if (num % i == 0) {
                stack.push(i);
                int newNum = num / i;
                helper(ans, newNum, Math.min(newNum, i), stack);
                stack.pop();
            }
        }
    }

    public static void main(String[] args) {
        Factors t = new Factors();
        List<List<Integer>> l = t.factorCombinations(24);
        for (List<Integer> li : l) {
            for (Integer i : li) {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值