Standard AC java backtracking, anyway to improve the performance?


  • 0
    F
    public List<List<Integer>> getFactors(int n) {
        List<List<Integer>> res = new LinkedList<List<Integer>>();
        if(n < 2) {return res;}
        helper(res,new LinkedList<Integer>(),n,2);
        return res;
    }
    public void helper(List<List<Integer>> res, List<Integer> cur_list, int n, int start){
        if(n == 1){
        /*avoid adding the number itself to the result*/
            if(cur_list.size() > 1){
                LinkedList<Integer> new_list = new LinkedList<Integer>(cur_list);
                res.add(new_list);
            }
            return;
        }
        for(int i = start; i <= n; i++){
            if(n % i == 0){
                cur_list.add(i);
                helper(res,cur_list,n/i,i);
                cur_list.remove(cur_list.size() - 1);
            }
        }
    }
    

    }


Log in to reply
 

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