[leetcode]Permutations

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].

【吐来个槽】还以为要输出题目中给出的顺序,折腾了很久发现,你妹,坑爹呢!哼╭(╯^╰)╮

算法思路:

思路2:

dfs

代码如下:

 1 public class Solution {
 2     List<List<Integer>> res = new ArrayList<List<Integer>>();
 3     public List<List<Integer>> permute(int[] num) {
 4         if(num == null || num.length == 0) return res;
 5         dfs(new ArrayList<Integer>(),num,new HashSet<Integer>());
 6         return res;
 7     }
 8     private void dfs(List<Integer> list,int[] num,Set<Integer> visited){
 9         if(list.size() == num.length){
10             res.add(new ArrayList<Integer>(list));
11             return;
12         }
13         for(int i = 0; i < num.length; i++){
14             if(visited.contains(num[i])) continue;
15             visited.add(num[i]);
16             list.add(num[i]);
17             dfs(list,num,visited);
18             visited.remove(num[i]);
19             list.remove(list.size() - 1);
20         }
21     }
22 }

 

 

 

思路1:

迭代,先求出(n - 1)的排列情况,继而求出n的。

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] num) {
 3         List<List<Integer>> result = new ArrayList<List<Integer>>();
 4         if(num == null || num.length == 0) return result;
 5         if(num.length == 1){
 6             List<Integer> list = new ArrayList<Integer>();
 7             list.add(num[0]);
 8             result.add(list);
 9             return result;
10         }
11         int[] pre = Arrays.copyOf(num, num.length - 1);
12         int tem = num[num.length - 1];
13         for(List<Integer> list : permute(pre)){
14             int newLength = list.size() + 1;
15             for(int i = 0; i < newLength; i++){
16                 List<Integer> newList = new ArrayList<Integer>();
17                 for(int j = 0; j < i;newList.add(list.get(j++)));
18                 newList.add(tem);
19                 for(int j = i; j < newLength - 1;newList.add(list.get(j++)));
20                 result.add(new ArrayList<Integer>(newList));
21             }
22         }
23         return result;
24     }
25 }

posted on 2014-07-22 16:26  喵星人与汪星人  阅读(209)  评论(0编辑  收藏  举报