-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathPermutations.java
More file actions
50 lines (46 loc) · 1.2 KB
/
Permutations.java
File metadata and controls
50 lines (46 loc) · 1.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
package leetcode;
import java.util.ArrayList;
import java.util.List;
/**
* @author eko
* @date 2018/10/22 10:14 AM
*
* Given a collection of distinct integers, return all possible permutations.
*
* Example:
*
* Input: [1,2,3]
* Output:
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
* ]
*/
public class Permutations {
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> res = new Permutations().permute(nums);
System.out.println(res);
}
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> list = new ArrayList<>();
backtrack(list, new ArrayList<>(), nums);
return list;
}
private void backtrack(List<List<Integer>> list, List<Integer> tempList, int[] nums) {
if (tempList.size() == nums.length) {
list.add(new ArrayList<>(tempList));
} else {
for (int i = 0; i < nums.length; i++) {
if (tempList.contains(nums[i])) continue;
tempList.add(nums[i]);
backtrack(list, tempList, nums);
tempList.remove(tempList.size() - 1);
}
}
}
}