首页 > 其他 > 详细

Permutations II

时间:2015-02-09 00:40:03      阅读:248      评论: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].

 1 public class Solution {
 2      public List<List<Integer>> permuteUnique(int[] num) {
 3          List<List<Integer>> result = new ArrayList<List<Integer>>();
 4          List<Integer> curr = new ArrayList<Integer>();
 5          Arrays.sort(num);
 6          dfs(result, curr, num, 0);
 7          return result;
 8      }
 9 
10      void dfs(List<List<Integer>> result, List<Integer> curr, int[] num, int index) {
11          if (index == num.length) {
12              if (!result.contains(curr)) {
13                 result.add(new ArrayList<Integer>(curr));
14 
15              }
16          } else {
17              for (int i = index; i <num.length ; i++) {
18                  if (noSwap(num,i,index)) {
19                      continue;
20                  } else {
21                      swap(num, i, index);
22                  }
23                  curr.add(num[index]);
24                  dfs(result, curr, num, index + 1);
25                  curr.remove(curr.size() - 1);
26                  swap(num, index,i );
27 
28              }
29 
30          }
31      }
32 
33      void swap(int[] num, int indexA, int indexB) {
34          int temp = num[indexA];
35          num[indexA] = num[indexB];
36          num[indexB] = temp;
37      }
38 
39      boolean noSwap(int[] num, int i, int j) {
40          for (int k = j; k < i; k++) {
41              if (num[k] == num[i]) {
42                  return true;
43              }
44          }
45          return false;
46      }
47 
48 }

 

Permutations II

原文:http://www.cnblogs.com/birdhack/p/4280680.html

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