45
45
46
46
<!-- 这里可写通用的实现逻辑 -->
47
47
48
- 深度优先搜索。
48
+ ** 方法一:DFS(回溯)**
49
+
50
+ 我们设计一个函数 $dfs(i)$ 表示已经填完了前 $i$ 个位置,现在需要填第 $i+1$ 个位置。枚举所有可能的数,如果这个数没有被填过,就填入这个数,然后继续填下一个位置,直到填完所有的位置。
51
+
52
+ 时间复杂度 $O(n\times n!)$,其中 $n$ 是数组的长度。一共有 $n!$ 个排列,每个排列需要 $O(n)$ 的时间来构造。
49
53
50
54
<!-- tabs:start -->
51
55
56
60
``` python
57
61
class Solution :
58
62
def permute (self , nums : List[int ]) -> List[List[int ]]:
63
+ return list (permutations(nums))
64
+ ```
65
+
66
+ ``` python
67
+ class Solution :
68
+ def permute (self , nums : List[int ]) -> List[List[int ]]:
69
+ def dfs (i ):
70
+ if i == n:
71
+ ans.append(t[:])
72
+ return
73
+ for j in range (n):
74
+ if not vis[j]:
75
+ vis[j] = True
76
+ t[i] = nums[j]
77
+ dfs(i + 1 )
78
+ vis[j] = False
79
+
59
80
n = len (nums)
60
- res = []
61
- path = [0 ] * n
62
- used = [False ] * n
81
+ vis = [False ] * n
82
+ t = [0 ] * n
83
+ ans = []
84
+ dfs(0 )
85
+ return ans
86
+ ```
63
87
64
- def dfs (u ):
65
- if u == n:
66
- res.append(path.copy())
88
+ ``` python
89
+ class Solution :
90
+ def permute (self , nums : List[int ]) -> List[List[int ]]:
91
+ def dfs (i ):
92
+ nonlocal mask
93
+ if i == n:
94
+ ans.append(t[:])
67
95
return
68
- for i in range (n):
69
- if not used[i] :
70
- path[u] = nums[i]
71
- used [i] = True
72
- dfs(u + 1 )
73
- used[i] = False
96
+ for j in range (n):
97
+ if (mask >> j & 1 ) == 0 :
98
+ mask |= 1 << j
99
+ t [i] = nums[j]
100
+ dfs(i + 1 )
101
+ mask ^= 1 << j
74
102
103
+ n = len (nums)
104
+ mask = 0
105
+ t = [0 ] * n
106
+ ans = []
75
107
dfs(0 )
76
- return res
108
+ return ans
77
109
```
78
110
79
111
### ** Java**
@@ -82,164 +114,157 @@ class Solution:
82
114
83
115
``` java
84
116
class Solution {
117
+ private List<List<Integer > > ans = new ArrayList<> ();
118
+ private List<Integer > t = new ArrayList<> ();
119
+ private boolean [] vis;
120
+ private int [] nums;
121
+
85
122
public List<List<Integer > > permute (int [] nums ) {
86
- List<List<Integer > > res = new ArrayList<> ();
87
- List<Integer > path = new ArrayList<> ();
88
- int n = nums. length;
89
- boolean [] used = new boolean [n];
90
- dfs(0 , n, nums, used, path, res);
91
- return res;
123
+ this . nums = nums;
124
+ vis = new boolean [nums. length];
125
+ dfs(0 );
126
+ return ans;
92
127
}
93
128
94
- private void dfs (
95
- int u , int n , int [] nums , boolean [] used , List<Integer > path , List<List<Integer > > res ) {
96
- if (u == n) {
97
- res. add(new ArrayList<> (path));
129
+ private void dfs (int i ) {
130
+ if (i == nums. length) {
131
+ ans. add(new ArrayList<> (t));
98
132
return ;
99
133
}
100
- for (int i = 0 ; i < n ; ++ i ) {
101
- if (! used[i ]) {
102
- path . add(nums[i]) ;
103
- used[i] = true ;
104
- dfs(u + 1 , n, nums, used, path, res );
105
- used[i] = false ;
106
- path . remove(path . size() - 1 ) ;
134
+ for (int j = 0 ; j < nums . length ; ++ j ) {
135
+ if (! vis[j ]) {
136
+ vis[j] = true ;
137
+ t . add(nums[j]) ;
138
+ dfs(i + 1 );
139
+ t . remove(t . size() - 1 ) ;
140
+ vis[j] = false ;
107
141
}
108
142
}
109
143
}
110
144
}
111
145
```
112
146
113
- ### ** JavaScript**
114
-
115
- ``` js
116
- /**
117
- * @param {number[]} nums
118
- * @return {number[][]}
119
- */
120
- var permute = function (nums ) {
121
- const n = nums .length ;
122
- let res = [];
123
- let path = [];
124
- let used = new Array (n).fill (false );
125
- dfs (0 , n, nums, used, path, res);
126
- return res;
127
- };
128
-
129
- function dfs (u , n , nums , used , path , res ) {
130
- if (u == n) {
131
- res .push (path .slice ());
132
- return ;
133
- }
134
- for (let i = 0 ; i < n; ++ i) {
135
- if (! used[i]) {
136
- path .push (nums[i]);
137
- used[i] = true ;
138
- dfs (u + 1 , n, nums, used, path, res);
139
- used[i] = false ;
140
- path .pop ();
141
- }
142
- }
143
- }
144
- ```
145
-
146
147
### ** C++**
147
148
148
149
``` cpp
149
150
class Solution {
150
151
public:
151
152
vector<vector<int >> permute(vector<int >& nums) {
152
153
int n = nums.size();
153
- vector<vector<int >> res;
154
- vector<int > path(n, 0);
155
- vector<bool > used(n, false);
156
- dfs(0, n, nums, used, path, res);
157
- return res;
154
+ vector<vector<int >> ans;
155
+ vector<int > t(n);
156
+ vector<bool > vis(n);
157
+ function<void(int)> dfs = [ &] (int i) {
158
+ if (i == n) {
159
+ ans.emplace_back(t);
160
+ return;
161
+ }
162
+ for (int j = 0; j < n; ++j) {
163
+ if (!vis[ j] ) {
164
+ vis[ j] = true;
165
+ t[ i] = nums[ j] ;
166
+ dfs(i + 1);
167
+ vis[ j] = false;
168
+ }
169
+ }
170
+ };
171
+ dfs(0);
172
+ return ans;
158
173
}
174
+ };
175
+ ```
176
+
177
+ ### **Go**
178
+
179
+ ```go
180
+ func permute(nums []int) (ans [][]int) {
181
+ n := len(nums)
182
+ t := make([]int, n)
183
+ vis := make([]bool, n)
184
+ var dfs func(int)
185
+ dfs = func(i int) {
186
+ if i == n {
187
+ cp := make([]int, n)
188
+ copy(cp, t)
189
+ ans = append(ans, cp)
190
+ return
191
+ }
192
+ for j, v := range nums {
193
+ if !vis[j] {
194
+ vis[j] = true
195
+ t[i] = v
196
+ dfs(i + 1)
197
+ vis[j] = false
198
+ }
199
+ }
200
+ }
201
+ dfs(0)
202
+ return
203
+ }
204
+ ```
159
205
160
- void dfs(int u, int n, vector<int>& nums, vector<bool>& used, vector<int>& path, vector<vector<int>>& res) {
161
- if (u == n) {
162
- res.emplace_back(path);
206
+ ### ** JavaScript**
207
+
208
+ ``` js
209
+ /**
210
+ * @param {number[]} nums
211
+ * @return {number[][]}
212
+ */
213
+ var permute = function (nums ) {
214
+ const n = nums .length ;
215
+ const ans = [];
216
+ const t = [];
217
+ const vis = new Array (n).fill (false );
218
+ function dfs (i ) {
219
+ if (i >= n) {
220
+ ans .push ([... t]);
163
221
return ;
164
222
}
165
- for (int i = 0 ; i < n; ++i) {
166
- if (!used[i]) {
167
- path[u] = nums[i];
168
- used[i] = true;
169
- dfs (u + 1, n, nums, used, path, res);
170
- used[ i] = false;
223
+ for (let j = 0 ; j < n; ++ j) {
224
+ if (! vis[j]) {
225
+ vis[j] = true ;
226
+ t .push (nums[j]);
227
+ dfs (i + 1 );
228
+ vis[j] = false ;
229
+ t .pop ();
171
230
}
172
231
}
173
232
}
233
+ dfs (0 );
234
+ return ans;
174
235
};
175
236
```
176
237
177
238
### ** C#**
178
239
179
240
``` cs
180
- using System .Collections .Generic ;
181
- using System .Linq ;
182
-
183
241
public class Solution {
184
242
public IList <IList <int >> Permute (int [] nums ) {
185
- var results = new List <IList <int >>();
186
- var temp = new List <int >();
187
- var visited = new bool [nums .Length ];
188
- Search (nums , visited , temp , results );
189
- return results ;
243
+ var ans = new List <IList <int >>();
244
+ var t = new List <int >();
245
+ var vis = new bool [nums .Length ];
246
+ dfs (nums , 0 , t , vis , ans );
247
+ return ans ;
190
248
}
191
249
192
- private void Search (int [] nums , bool [] visited , IList <int > temp , IList <IList <int >> results )
193
- {
194
- int count = 0 ;
195
- for (var i = 0 ; i < nums .Length ; ++ i )
196
- {
197
- if (visited [i ]) continue ;
198
- ++ count ;
199
- temp .Add (nums [i ]);
200
- visited [i ] = true ;
201
- Search (nums , visited , temp , results );
202
- temp .RemoveAt (temp .Count - 1 );
203
- visited [i ] = false ;
250
+ private void dfs (int [] nums , int i , IList <int > t , bool [] vis , IList <IList <int >> ans ) {
251
+ if (i >= nums .Length ) {
252
+ ans .Add (new List <int >(t ));
253
+ return ;
204
254
}
205
- if (count == 0 && temp .Any ())
206
- {
207
- results .Add (new List <int >(temp ));
255
+ for (int j = 0 ; j < nums .Length ; ++ j ) {
256
+ if (! vis [j ]) {
257
+ vis [j ] = true ;
258
+ t .Add (nums [j ]);
259
+ dfs (nums , i + 1 , t , vis , ans );
260
+ t .RemoveAt (t .Count - 1 );
261
+ vis [j ] = false ;
262
+ }
208
263
}
209
264
}
210
265
}
211
266
```
212
267
213
- ### ** Go**
214
-
215
- ``` go
216
- func permute (nums []int ) [][]int {
217
- n := len (nums)
218
- res := make ([][]int , 0 )
219
- path := make ([]int , n)
220
- used := make ([]bool , n)
221
- dfs (0 , n, nums, used, path, &res)
222
- return res
223
- }
224
-
225
- func dfs (u , n int , nums []int , used []bool , path []int , res *[][]int ) {
226
- if u == n {
227
- t := make ([]int , n)
228
- copy (t, path)
229
- *res = append (*res, t)
230
- return
231
- }
232
- for i := 0 ; i < n; i++ {
233
- if !used[i] {
234
- path[u] = nums[i]
235
- used[i] = true
236
- dfs (u+1 , n, nums, used, path, res)
237
- used[i] = false
238
- }
239
- }
240
- }
241
- ```
242
-
243
268
### ** TypeScript**
244
269
245
270
``` ts
0 commit comments