LeetCode刷题笔录 Permutaions

来源:互联网 发布:u3软件 编辑:程序博客网 时间:2024/06/05 00:51
不用递归的解法自己想不出来,在这里
public class Solution {    public ArrayList<ArrayList<Integer>> permute(int[] num) {        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();        //start from an empty list        result.add(new ArrayList<Integer>());        for (int i = 0; i < num.length; i++) {            //list of list in current iteration of the array num            ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();for (ArrayList<Integer> l : result) {                // # of locations to insert is largest index + 1                for (int j = 0; j < l.size()+1; j++) {                    // + add num[i] to different locations                    l.add(j, num[i]);                    ArrayList<Integer> temp = new ArrayList<Integer>(l);                    current.add(temp);                    // - remove num[i] add                    l.remove(j);                }            }            result = new ArrayList<ArrayList<Integer>>(current);        }        return result;    }}
0 0