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


Solution:

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] num) {
 3         List<List<Integer>> result=new ArrayList<List<Integer>>();
 4         List<Integer> al=new ArrayList<Integer>();
 5         boolean[] flag=new boolean[num.length];
 6         dfs(num,result,al,0,flag);
 7         return result;
 8     }
 9 
10     private void dfs(int[] num, List<List<Integer>> result, List<Integer> al, int level,boolean[] flag) {
11         // TODO Auto-generated method stub
12         if(level>num.length)
13             return;
14         if(level==num.length){
15             result.add(new ArrayList<Integer>(al));
16             return;
17         }
18         for(int i=0;i<num.length;++i){
19             if(!flag[i]){
20                 flag[i]=true;
21                 al.add(num[i]);
22                 dfs(num, result, al, level+1, flag);
23                 al.remove(al.size()-1);
24                 flag[i]=false;
25             }
26         }    
27     }
28 }

 

posted @ 2014-11-13 06:05  Phoebe815  阅读(174)  评论(0编辑  收藏  举报