Java non-recursion using queue and stack


  • 0
    G
        public List<List<Integer>> getFactors(int n) {
            List<List<Integer>> result = new ArrayList<>();
            if (n <= 2) {
                return result;
            }
            Queue<Stack<Integer>> queue = new LinkedList<Stack<Integer>>();
            Stack<Integer> starter = new Stack<Integer>();
            starter.push(n);
            queue.offer(starter);
            while (!queue.isEmpty()) {
                Stack<Integer> current = queue.poll();
                if (current.size() > 1) {
                    result.add(new ArrayList<Integer>(current));
                }
                int toFactor = current.pop();
                for (int i = 2; i <= Math.sqrt(toFactor); i++) {
                    if (toFactor % i != 0) {
                        continue;
                    }
                    if (current.size() > 0 && current.peek() > i) {
                        continue;
                    }
                    current.push(i);
                    current.push(toFactor / i);
                    queue.offer((Stack<Integer>) current.clone());
                    current.pop();
                    current.pop();
                }
            }
            return result;
        }
    

Log in to reply
 

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