forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_46.java
51 lines (43 loc) · 1.26 KB
/
_46.java
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
package com.fishercoder.solutions;
import java.util.ArrayList;
import java.util.List;
/**
* 46. Permutations
*
* Given a collection of distinct numbers, return all possible permutations.
For example,
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
*/
public class _46 {
public static class Solution1 {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList();
result.add(new ArrayList<>());
return backtracking(result, nums, 0);
}
private List<List<Integer>> backtracking(List<List<Integer>> result, int[] nums, int pos) {
if (pos == nums.length) {
return result;
}
List<List<Integer>> newResult = new ArrayList();
for (List<Integer> eachList : result) {
for (int i = 0; i <= eachList.size(); i++) {
//attn: i starts from 0
List<Integer> newList = new ArrayList(eachList);
newList.add(i, nums[pos]);
newResult.add(newList);
}
}
result = newResult;
return backtracking(result, nums, pos + 1);
}
}
}