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


DFS的题, 感觉有点像是八皇后问题的变形。 程序的框架和思想也差不多。


public class Solution {
    public ArrayList<ArrayList<Integer>> permute(int[] num) {
           ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
           permute(num,0,result);
           return result;
    }
    public void swap(int[] num,int a,int b){
        int tp = num[a];
        num[a] = num[b];
        num[b] = tp;
    }
    public void permute(int[] num, int level, ArrayList<ArrayList<Integer>> result) {
           int length = num.length;
           if(level==length){
               ArrayList<Integer> current= new ArrayList<Integer>();
               for(int el:num){
                   current.add(el);
               }
               result.add(current);
           }else{
               permute(num,level+1,result);
               for(int i=level+1;i<length;i++){
                    swap(num, i,level);
                    permute(num,level+1,result);
                    swap(num, i,level);
               }
           }
    }
}

你可能感兴趣的:(java,LeetCode,Permutations)