Short iterative Java solution with comments


  • 1
    S

    Hi guys!

    There's no secret how to make an iterative generation of all permutations, which is greatly described in other posts. Here I just tried to minimize the size of a Java code but keeping it readable and easy to understand.

    public List<List<Integer>> permute(int[] num) {
        LinkedList ans = new LinkedList<>(); // queue
        ans.offer(new LinkedList<Integer>()); // init with empty list
        // loop through sizes of lists used for inserting new element in asc order
        for (int n = 0; n < num.length; n++) { 
            // loop through all lists of a current size
            while (n == ans.peek().size()) {
                List<Integer> l = ans.poll(); // next "base" list of a curr size
                // loop through all position in a "base" list generating new list
                for (int i = 0; i <= l.size(); i++) {
                    LinkedList<Integer> newL = new LinkedList<>(l.subList(0,i));
                    newL.add(num[n]);
                    newL.addAll(l.subList(i,l.size()));
                    ans.offer(newL);
                }
            }
        }
        return ans;
    }
    

    Happy coding!


Log in to reply
 

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