Share my short iterative JAVA solution


  • 55
    T
    public List<List<Integer>> permute(int[] num) {
        LinkedList<List<Integer>> res = new LinkedList<List<Integer>>();
        res.add(new ArrayList<Integer>());
        for (int n : num) {
            int size = res.size();
            for (; size > 0; size--) {
                List<Integer> r = res.pollFirst();
                for (int i = 0; i <= r.size(); i++) {
                    List<Integer> t = new ArrayList<Integer>(r);
                    t.add(i, n);
                    res.add(t);
                }
            }
        }
        return res;
    }

  • 0
    H
    This post is deleted!

  • 0
    M

    what about time complexity ?


  • 0
    R

    i can‘t understand your idea,can you explain it ,chanese is ok!


  • 9
    S

    @ruo 就是遍历nums(第一个for loop),当开始进行nums[i]时,res中的结果是nums[0]至nums[i-1]的全排列。每一次循环中,需要将nums[i]加入到res中的每一个结果中的每一个位置,然后开始下一次循环。具体做法是,每一次循环开始,先记录当前res的大小(size),取出res中的第一个,在每个位置添加nums[i]然后加到res末尾(第三个for loop,循环r.size()次),一共进行size次(第二个for loop)。


  • 0
    A

    @ruo what is chanese?


  • 0
    X

    @sunjiaqi Well explained


Log in to reply
 

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