首页 > 其他 > 详细

[Leetcode] Permutations II

时间:2014-11-13 06:58:45      阅读:117      评论:0      收藏:0      [点我收藏+]

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

 

Solution:

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

 

[Leetcode] Permutations II

原文:http://www.cnblogs.com/Phoebe815/p/4093981.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!