Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Latest commit

Β 

History

History
History
73 lines (52 loc) Β· 1.59 KB

File metadata and controls

73 lines (52 loc) Β· 1.59 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package medium;
import java.util.ArrayList;
import java.util.List;
public class Permutations46 {
public static List<List<Integer>> permute1(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
ArrayList<Integer> templist = new ArrayList<>();
permute1(nums, templist, list);
return list;
}
private static void permute1(int[] nums, List<Integer> temp, List<List<Integer>> list) {
if (temp.size() == nums.length) {
list.add(new ArrayList<>(temp));
return;
}
for (int i = 0; i < nums.length; i++) {
if (temp.contains(nums[i]))
continue;
temp.add(nums[i]);
permute1(nums, temp, list);
temp.remove(temp.size() - 1);
}
}
// O(N!) Time - using visited mark
public static List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
backtrack(nums, visited, new ArrayList<Integer>(), result);
return result;
}
private static void backtrack(int[] nums, boolean[] visited, ArrayList<Integer> permutations,
List<List<Integer>> result) {
if (permutations.size() == nums.length) {
result.add(new ArrayList<>(permutations)); // deep-copy
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i] == true)
continue;
permutations.add(nums[i]);
visited[i] = true;
backtrack(nums, visited, permutations, result);
permutations.remove(permutations.size() - 1); // remove recently
// visited
visited[i] = false;
}
}
public static void main(String[] args) {
int[] nums = { 1, 2, 3 };
System.out.println(permute(nums));
}
}
Morty Proxy This is a proxified and sanitized view of the page, visit original site.