-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_0046Permutations.java
More file actions
76 lines (64 loc) · 2.2 KB
/
_0046Permutations.java
File metadata and controls
76 lines (64 loc) · 2.2 KB
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
74
75
76
package com.heatwave.leetcode.problems;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class _0046Permutations {
static class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
boolean[] used = new boolean[nums.length];
backtracking(nums, used);
return ans;
}
private void backtracking(int[] nums, boolean[] used) {
if (temp.size() == nums.length) {
ans.add(new ArrayList<>(temp));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]) {
continue;
}
temp.add(nums[i]);
used[i] = true;
backtracking(nums, used);
temp.remove(temp.size() - 1);
used[i] = false;
}
}
}
static class InPlaceSolution {
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
backtracking(nums, 0);
return ans;
}
private void backtracking(int[] nums, int index) {
if (index == nums.length) {
ans.add(Arrays.stream(nums).boxed().collect(Collectors.toList()));
return;
}
for (int i = index; i < nums.length; i++) {
swap(nums, index, i);
backtracking(nums, index + 1);
swap(nums, index, i);
}
}
private void swap(int[] nums, int i, int j) {
int temp = nums[j];
nums[j] = nums[i];
nums[i] = temp;
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {1, 2, 3};
List<List<Integer>> permute = solution.permute(nums);
System.out.println(permute);
InPlaceSolution inPlaceSolution = new InPlaceSolution();
List<List<Integer>> permute1 = inPlaceSolution.permute(nums);
System.out.println(permute1);
}
}