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     ArrayList<ArrayList<Integer>> result = null;
 3     int len = 0;
 4     public ArrayList<ArrayList<Integer>> permute(int[] num) {
 5         // Start typing your Java solution below
 6         // DO NOT write main() function
 7         result = new ArrayList<ArrayList<Integer>>();
 8         if(num == null || num.length == 0) return result;
 9         len = num.length;
10         boolean[] item = new boolean[len];
11         get(item, num, new ArrayList<Integer>());
12         return result;
13     }
14     public void get(boolean[] item, int[] num, ArrayList<Integer> row){
15         if(row.size() == len){
16             result.add(new ArrayList<Integer>(row));
17             return;
18         }
19         for(int i = 0; i < len; i ++){
20             if(!item[i]){
21                 item[i] = true;
22                 row.add(num[i]);
23                 get(item, num, row);
24                 item[i] = false;
25                 row.remove(row.size() - 1);  
26             }
27         }
28     }
29 }

 第三遍:

 1 public class Solution {
 2     public List<List<Integer>> permute(int[] num) {
 3         ArrayList<List<Integer>> result = new ArrayList<List<Integer>>();
 4         getPermutation(num, num.length, new ArrayList<Integer>(), result);
 5         return result;
 6     }
 7     public void getPermutation(int[] num, int len, ArrayList<Integer> row, ArrayList<List<Integer>> result){
 8         if(num == null || len == 0){
 9             result.add(row);
10             return;
11         }
12         for(int i = 0; i < len; i ++){
13             ArrayList<Integer> nrow = new ArrayList<Integer>(row);
14             nrow.add(num[i]);
15             int tmp = num[i];
16             num[i] = num[len - 1];
17             getPermutation(num, len - 1, nrow, result);
18             num[i] = tmp;
19         }
20     }
21 }

 

posted on 2013-10-11 11:56  Step-BY-Step  阅读(179)  评论(0编辑  收藏  举报

导航