File tree 2 files changed +57
-1
lines changed
solution/047.Permutations II
2 files changed +57
-1
lines changed Original file line number Diff line number Diff line change 9
9
10
10
<h2 align =" center " >LeetCode Solution</h2 >
11
11
12
- ## Introduction
13
12
Complete solutions to Leetcode problems, updated daily.
14
13
15
14
## Solution List
Original file line number Diff line number Diff line change 19
19
20
20
注意:第 i 个数字与第 j 个数字交换时,要求[ i, j) 中没有与第 j 个数字相等的数。
21
21
22
+ 解法①:
23
+
22
24
``` java
23
25
class Solution {
24
26
public List<List<Integer > > permuteUnique (int [] nums ) {
@@ -66,4 +68,59 @@ class Solution {
66
68
nums[j] = t;
67
69
}
68
70
}
71
+ ```
72
+
73
+ 解法②:
74
+
75
+ ``` java
76
+ class Solution {
77
+ public List<List<Integer > > permuteUnique (int [] nums ) {
78
+ List<List<Integer > > list = new ArrayList<> ();
79
+ permute(list, nums, 0 );
80
+ return list;
81
+ }
82
+
83
+ private void permute (List<List<Integer > > list , int [] nums , int start ) {
84
+ int end = nums. length - 1 ;
85
+ if (start == end) {
86
+ List<Integer > tmp = new ArrayList<> ();
87
+ for (int val : nums) {
88
+ tmp. add(val);
89
+ }
90
+
91
+ list. add(tmp);
92
+
93
+ }
94
+
95
+
96
+ int max = Integer . MIN_VALUE ;
97
+ int min = Integer . MAX_VALUE ;
98
+ for (int i = 0 ; i <= end; ++ i) {
99
+ max = Math . max(max, nums[i]);
100
+ min = Math . min(min, nums[i]);
101
+ }
102
+ // 空间换取时间
103
+ boolean [] flag = new boolean [max - min + 1 ];
104
+
105
+ for (int i = start; i <= end; ++ i) {
106
+ int index = nums[i] - min;
107
+ if (! flag[index]) {
108
+ // 说明当前的数没在之前出现过
109
+ swap(nums, i, start);
110
+ permute(list, nums, start + 1 );
111
+ swap(nums, i, start);
112
+
113
+ // 标志位设为 true
114
+ flag[index] = true ;
115
+ }
116
+ }
117
+
118
+ }
119
+
120
+ private void swap (int [] nums , int i , int j ) {
121
+ int t = nums[i];
122
+ nums[i] = nums[j];
123
+ nums[j] = t;
124
+ }
125
+ }
69
126
```
You can’t perform that action at this time.
0 commit comments