Java, recursive, simple


  • 0
    A
    List<List<Integer>> res = new ArrayList<>();
    
    public List<List<Integer>> getFactors(int n) {
        getFactors(n, new ArrayList<Integer>());
        res.remove(res.size() - 1);
        return res;
    }
    
    private void getFactors(int n, List<Integer> a) {
        if (n == 1) res.add(new ArrayList<Integer>(a));
        for (int i = 2; i <= n; i++) {
            if (n % i == 0 && (n / i >= i || n / i == 1) 
                && !(a.size() > 0 && a.get(a.size() - 1) > i)) {
                a.add(i);
                getFactors(n / i, a);
                a.remove(a.size() - 1);
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.