forked from forging2012/JavaArithmetic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode47.java
More file actions
63 lines (48 loc) · 1.65 KB
/
LeetCode47.java
File metadata and controls
63 lines (48 loc) · 1.65 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
51
52
53
54
55
56
57
58
59
60
61
62
63
package LeetCode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class LeetCode47 {
//https://leetcode-cn.com/problems/permutations/description/
// 全排列
private ArrayList<List<Integer>> res;
private boolean[] used;
public List<List<Integer>> permute(int[] nums) {
res = new ArrayList<>();
if (nums == null || nums.length == 0)
return res;
used = new boolean[nums.length];
LinkedList<Integer> p = new LinkedList<>();
generatePermutation(nums, 0, p);
return res;
}
// p中保存了一个有index-1个元素的排列。
// 向这个排列的末尾添加第index个元素, 获得一个有index个元素的排列
private void generatePermutation(int[] nums, int index, LinkedList<Integer> p) {
if (index == nums.length) {
res.add((List<Integer>) p.clone());
return;
}
for (int i = 0; i < nums.length; i++)
if (!used[i]) {
used[i] = true;
p.addLast(nums[i]);
generatePermutation(nums, index + 1, p);
// 回溯完要清除状态
p.removeLast();
used[i] = false;
}
return;
}
private static void printList(List<Integer> list) {
for (Integer e : list)
System.out.print(e + " ");
System.out.println();
}
public static void main(String[] args) {
int[] nums = {1, 2, 3};
List<List<Integer>> res = (new LeetCode47()).permute(nums);
for (List<Integer> list : res)
printList(list);
}
}