首页 > 其他 > 详细

Permutations II

时间:2014-02-08 09:21:12      阅读:310      评论: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].

bubuko.com,布布扣
 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> permuteUnique(int[] num) {
 3         ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
 4             boolean [] visited = new boolean[num.length];
 5             Arrays.sort(num);
 6             DFS(num,visited,0,res,new ArrayList<Integer>());
 7             return res;
 8         }
 9         public void DFS(int []num,boolean[] visited,int start,ArrayList<ArrayList<Integer>>res,ArrayList<Integer>output){
10             if(start ==num.length){
11                 ArrayList<Integer> temp = new ArrayList<Integer>();
12                 temp.addAll(output);
13                 res.add(temp);
14                 return;
15             }
16             for(int i=0;i<num.length;i++){
17                 if(!visited[i] ){
18                     if(i>0 && num[i-1]==num[i] && !visited[i-1]) 
19                         continue;
20                     visited[i] = true;
21                     output.add(num[i]);
22                     DFS(num,visited,start+1,res,output);
23                     output.remove(output.size()-1);
24                     visited[i] = false;
25                     }
26                 }
27        }
28 
29     
30 }
View Code

Permutations II

原文:http://www.cnblogs.com/krunning/p/3540025.html

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