Java easy to understand recursive solution.


  • 0
    C
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> ret = new ArrayList<>();
        if (n == 1) {
            return ret;
        }
        List<Integer> nums = factors(n);
        dfs(nums, n, 1, 0, new ArrayList<>(), ret);
        return ret;
    }
    
    private void dfs(List<Integer> nums, int n, int cur, int idx, List<Integer> path, List<List<Integer>> ret) {
        if (cur >= n) {
            if (cur == n) {
                ret.add(path);
            }
            return; // backtracking
        }
        for (int i = idx; i < nums.size(); i++) {
            List<Integer> p = new ArrayList<>(path);
            p.add(nums.get(i));
            dfs(nums, n, cur*nums.get(i), i, p, ret);
        }
    }
    private List<Integer> factors(int n) {
        List<Integer> ret = new ArrayList<>();
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                ret.add(i);
            }
        }
        return ret;
    }

Log in to reply
 

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