-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPermutationsM2.java
More file actions
38 lines (33 loc) · 1.04 KB
/
PermutationsM2.java
File metadata and controls
38 lines (33 loc) · 1.04 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
package Backtracking;
import java.util.*;
class Solution {
public void helper(int[] nums, List<Integer> ds, boolean[] isValid, List<List<Integer>> ans) {
int n = nums.length;
if (ds.size() == n) {
List<Integer> list = new ArrayList<>();
for (int i = 0; i < ds.size(); i++) {
list.add(ds.get(i));
}
ans.add(list);
return;
}
for (int i = 0; i < nums.length; i++) {
if (isValid[i] == false) {
ds.add(nums[i]);
isValid[i] = true;
helper(nums, ds, isValid, ans);
isValid[i] = false;
ds.remove(ds.size() - 1);
}
}
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ds = new ArrayList<>();
boolean[] isValid = new boolean[nums.length];
helper(nums, ds, isValid, ans);
return ans;
}
public static void main(String[] args) {
}
}