FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
coding-Interview/Permutations.java at master · arjunmullick/coding-Interview · GitHub
arjunmullick
/
coding-Interview
Public
Notifications
You must be signed in to change notification settings
Fork
1
Star
3
Code
Issues
0
Pull requests
0
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Expand file tree
Breadcrumbs
coding-Interview
/
Permutations.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
40 lines (35 loc) · 1.3 KB
Breadcrumbs
coding-Interview
/
Permutations.java
Copy path
File metadata and controls
40 lines (35 loc) · 1.3 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package
com
.
leetcode
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
List
;
public
class
Permutations
{
//https://leetcode.com/problems/permutations/
/**
Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
**/
class
Solution
{
public
List
<
List
<
Integer
>>
permute
(
int
[]
nums
) {
List
<
List
<
Integer
>>
result
=
new
ArrayList
<>();
List
<
Integer
>
list
=
new
ArrayList
<>();
//first list
for
(
int
n
:
nums
){
list
.
add
(
n
);
}
backtrack
(
0
,
nums
,
list
,
result
);
return
result
;
}
public
void
backtrack
(
int
index
,
int
[]
nums
,
List
<
Integer
>
list
,
List
<
List
<
Integer
>>
result
){
if
(
index
==
list
.
size
())
//the recursion start swaping from last element
result
.
add
(
new
ArrayList
<>(
list
));
//copy and add
for
(
int
i
=
index
;
i
<
nums
.
length
;
i
++){
swap
(
list
,
index
,
i
);
//swap all other with this index
backtrack
(
index
+
1
,
nums
,
list
,
result
);
swap
(
list
,
index
,
i
);
//reset
}
}
private
void
swap
(
List
<
Integer
>
list
,
int
index1
,
int
index2
){
int
temp
=
list
.
get
(
index1
);
list
.
set
(
index1
,
list
.
get
(
index2
));
list
.
set
(
index2
,
temp
);
}
}
}
Back
|
FazBrowse Home
|
New Git URL