-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLC46-Permutation.java
More file actions
47 lines (34 loc) · 1.17 KB
/
Copy pathLC46-Permutation.java
File metadata and controls
47 lines (34 loc) · 1.17 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
import java.util.ArrayList;
import java.util.List;
import java.util.Arrays;
/**
* Solution for Leetcode #46: Permutations
* Time Complexity: O(n * n!)
* Space Complexity: O(n)
*/
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
int lenghtOfInput = nums.length;
// Empty case
if(nums != null && lenghtOfInput < 1) return result;
boolean[] used = new boolean[lenghtOfInput];
backtrack(nums, new ArrayList<Integer>(), used, result);
return result;
}
private void backtrack(int[] input, List<Integer> currentList, boolean[] used, List<List<Integer>> result) {
int lenghtOfInput = input.length;
if(currentList.size() == lenghtOfInput) {
result.add(new ArrayList<>(currentList));
return;
}
for(int i=0; i < lenghtOfInput; i++) {
if(used[i]) {continue;}
used[i] = true;
currentList.add(input[i]);
backtrack(input, currentList, used, result);
currentList.remove(currentList.size() - 1);
used[i] = false;
}
}
}