7
7
* Description:
8
8
*
9
9
* Given a collection of numbers that might contain duplicates, return all
10
- * possible uniquepermutations .
10
+ * possible uniquesubs .
11
11
*
12
12
* For example,
13
- * [1,1,2] have the following uniquepermutations :
13
+ * [1,1,2] have the following uniquesubs :
14
14
* [1,1,2], [1,2,1], and [2,1,1].
15
15
*
16
16
***************************************************************************
17
- * {@link https://leetcode.com/problems/permutations -ii/ }
17
+ * {@link https://leetcode.com/problems/subs -ii/ }
18
18
* P.S.: cannot skip duplicates using while (nums[i] == duplicate) because
19
19
* after swapping, duplicates may be separated (one duplicate is swapped with
20
20
* and goes to somewhere else disconnected with other duplicates)
@@ -37,44 +37,44 @@ public List<List<Integer>> permuteUnique(int[] nums) {
37
37
}
38
38
Arrays .sort (nums );
39
39
int index =0 ;
40
- List <Integer >permutation =new ArrayList <Integer >();
41
- permuteUnique (nums ,index ,permutation ,result );
40
+ List <Integer >sub =new ArrayList <Integer >();
41
+ permuteUnique (nums ,index ,sub ,result );
42
42
return result ;
43
43
}
44
44
45
- private void permuteUnique (int []nums ,int index ,
46
- List <Integer >permutation ,List <List <Integer >>result ) {
47
-
45
+ private void permuteUnique (int []nums ,int index ,List <Integer >sub ,
46
+ List <List <Integer >>result ) {
48
47
// base case
49
48
if (index ==nums .length ) {
50
- // one validpermutation found
51
- result .add (permutation );
49
+ // one validsub found
50
+ result .add (sub );
52
51
return ;
53
52
}
54
53
55
54
// recursive case
56
55
// either use set or sort nums[index]:nums[end] to avoid duplicates
57
56
Set <Integer >appearred =new HashSet <Integer >();
58
57
for (int i =index ;i <nums .length ;i ++) {
59
- // try each number among nums[index],...,nums[end]
60
- // as permutation[index], remember to skip duplicates!
61
- if (appearred .contains (nums [i ]) ==false ) {
62
- // swap nums[i] with nums[index]
63
- swap (nums ,i ,index );
58
+ if (appearred .contains (nums [i ])) {
59
+ // duplicates appear
60
+ continue ;
61
+ }
62
+ appearred .add (nums [i ]);
63
+ // swap nums[i] with nums[index]
64
+ swap (nums ,i ,index );
64
65
65
- // go on searching
66
- List <Integer >copy =new ArrayList <Integer >(permutation );
67
- copy .add (nums [index ]);
68
- permuteUnique (nums ,index +1 ,copy ,result );
66
+ // go on searching
67
+ List <Integer >copy =new ArrayList <Integer >(sub );
68
+ copy .add (nums [index ]);
69
+ permuteUnique (nums ,index +1 ,copy ,result );
69
70
70
- // swap back nums[i] with nums[index]
71
- swap (nums ,index ,i );
71
+ // swap back nums[i] with nums[index]
72
+ swap (nums ,index ,i );
72
73
73
- appearred .add (nums [i ]);
74
- }
75
74
}
76
75
}
77
76
77
+ // swap two numbers in an array
78
78
private void swap (int []nums ,int i ,int index ) {
79
79
if (i <nums .length &&index <nums .length ) {
80
80
int temp =nums [i ];