Easy Java 2ms Backtracking solution


  • 0
    L
    public class Solution {
        public List<List<Integer>> getFactors(int n) {
            List<List<Integer>> res = new ArrayList<>();
            if(n == 1) {
                return res;
            }
            List<Integer> comb = new ArrayList<Integer>();
            helper(res, comb, 2, n);
            return res;
        }
        
        public void helper(List<List<Integer>> res, List<Integer> comb, int start, int n){
            if(n == 0){
                return;
            } else if(comb.size() != 0){
                comb.add(n);
                res.add(new ArrayList<Integer>(comb));
                comb.remove(comb.size() - 1);
            }
            for(int i = start; i <= Math.sqrt(n); ++i){
                if(n % i != 0) {continue;}
                comb.add(i);
                helper(res, comb, i, n / i);
                comb.remove(comb.size() - 1);
            }
        }
    }
    

Log in to reply
 

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