My Simple and clean Java solution


  • 0
    G
    public class Solution {
        public List<List<Integer>> getFactors(int n) {
            List<List<Integer>> res = new ArrayList();
            if ( n <= 2){
                return res;
            }
            dfs(new ArrayList(), n, res);
            return res;
        }
        
        public void dfs(List<Integer> path, int n, List<List<Integer>> res){
            if (path.size() >= 1){
                List<Integer> newPath = new ArrayList(path);
                newPath.add(n);
                res.add(newPath);
            }
            int start = path.size() == 0 ? 2 :  path.get(path.size()-1);
            for (int i = start; i <= Math.sqrt(n); i++){
                if (n % i == 0){
                    path.add(i);
                    dfs(path, n / i, res);
                    path.remove(path.size()-1);
                }
            }
        }
    }
    

Log in to reply
 

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