1. 程式人生 > >求一個數組的全排列

求一個數組的全排列

import java.util.*;
public class Solution {
   static ArrayList<ArrayList<Integer>> result;
    public ArrayList<ArrayList<Integer>> permute(int[] num) {  
        result = new ArrayList<ArrayList<Integer>>();
        if(num==null || num.length==0)
            return result;
        Arrays.sort(num);
        ArrayList<Integer> list =  new ArrayList<>();
        addnum(list,num);
        return result;
    }
    public static void addnum(ArrayList<Integer> list, int[] num){
        if(list.size() == num.length){
            result.add(new ArrayList<Integer>(list));
            return ;
        }
        for(int i=0;i<num.length;i++){
            if(!list.contains(num[i])){
                list.add(num[i]);
                addnum(list,num);  
                list.remove(list.size() - 1);
          }          
        }
    }
}