1~2ms Java backtrack optimal solution. Beats more than 90% other solutions


  • 0
    public class Solution {
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> result = new ArrayList<List<Integer>>();
        List<Integer> dfs = new ArrayList<Integer>();
        getFactorsHelper(result,dfs,n, 2);
        return result;
    }
    public void getFactorsHelper(List<List<Integer>> result,List<Integer> dfs, int target, int startFactor){
        for(int factor = startFactor; factor<=target/factor; factor++)
            if(target%factor==0){
                dfs.add(factor);
                getFactorsHelper(result,dfs,target/factor, factor);
                dfs.add(target/factor);
                result.add(new ArrayList<Integer>(dfs));
                dfs.remove(dfs.size()-1);
                dfs.remove(dfs.size()-1);
            }
    }
    

    }


Log in to reply
 

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