LeetCode Permutations

Given a collection of numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:
[1,2,3][1,3,2][2,1,3][2,3,1][3,1,2], and [3,2,1].

采用递归的思路,一次加一个数,每次更新上一次的结果。

 1 public class Solution {
 2 
 3     public List<List<Integer>> permute(int[] num) {
 4         List<List<Integer>> lastList=new ArrayList<List<Integer>>();
 5         List<List<Integer>> currList=new ArrayList<List<Integer>>();
 6             if (num==null) {
 7                 return lastList;
 8             }
 9             
10             List<Integer> eleList=new ArrayList<>();
11             eleList.add(num[0]);
12             lastList.add(eleList);
13             
14             if (num.length==1) {
15                 return lastList;
16             }
17             for (int i = 1; i < num.length; i++) {
18                 for (List<Integer> l : lastList) {
19                     currList.addAll(insertList(num[i], l));
20                     
21                 }
22                 lastList.clear();
23                 lastList.addAll(currList);
24                 currList.clear();
25         }
26             return lastList;
27             
28     }
29     
30     private List<List<Integer>> insertList(int num,List<Integer> list) {
31             List<List<Integer>> retNew=new ArrayList<List<Integer>>();
32             
33             for (int i = 0; i <= list.size(); i++) {
34                     List<Integer> currlist=new ArrayList<>();
35                 currlist.addAll(list);
36                 currlist.add(i, num);
37                 retNew.add(currlist);
38                 currlist=null;
39             }
40             return retNew;
41         
42     }
43 }
原文地址:https://www.cnblogs.com/birdhack/p/4032287.html