leetcode------Permutations II ★★★★★★★★★不会

标题: Permutations II
通过率: 25.7%
难度:

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

 

 

 

看别人的也没有看懂什么意思

 1 public class Solution {

 2     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {

 3           ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();

 4         dfs(res,num,0);

 5         return res;

 6         

 7     }

 8     public void dfs(ArrayList<ArrayList<Integer>> res,int[] num,int start){

 9         if(start==num.length){

10             ArrayList<Integer> tmp=new ArrayList<Integer>();

11             for(int i=0;i<num.length;i++){

12                 tmp.add(num[i]);

13             }

14                 res.add(tmp);

15         }

16         for(int j=start;j<num.length;j++){

17             if(cons(num,start,j)){

18             swap(num,j,start);

19             dfs(res,num,start+1);

20             swap(num,j,start);

21             }

22         }

23     }

24     public void swap(int []num,int a,int b){

25         if(num[a]!=num[b]){

26         int tmp=num[a];

27         num[a]=num[b];

28         num[b]=tmp;

29         }

30     }

31     public boolean cons(int [] num,int start,int end){

32         for(int i=start;i<end;i++){

33             if(num[i]==num[end])return false;

34         }

35         return true;

36     }

37 }

 

你可能感兴趣的:(LeetCode)