Permutations

Leetcode 46.

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
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> ans = new ArrayList<>();
int numsLength = nums.length;
if(numsLength == 1){
List<Integer> list = new ArrayList<Integer>();
list.add(nums[0]);
ans.add(list);
return ans;
}
List<Integer> store = new ArrayList<>();
boolean[] visited = new boolean[numsLength];
backtricking(ans,store,nums,visited);
return ans;
}
public void backtricking(List<List<Integer>> ans, List<Integer> store,int[] nums,boolean[] visited){
//recursion stop condition
if(store.size() == nums.length){
//collect data
List<Integer> list = new ArrayList<>();
list.addAll(store);
ans.add(list);
return;
}
for(int i = 0; i < nums.length;i++){
if(visited[i]){
continue;
}
visited[i] = true;
store.add(nums[i]);
//recursion
backtricking(ans,store,nums,visited);
//undo previous operation
store.remove(store.size() - 1);

visited[i] = false;
}

}
}