forked from algorithm019/algorithm019
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermute.java
More file actions
39 lines (35 loc) · 1.11 KB
/
permute.java
File metadata and controls
39 lines (35 loc) · 1.11 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
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author libingc
* @date 2020/11/23
*/
//给定一个 没有重复 数字的序列,返回其所有可能的全排列。
public class permute {
public List<List<Integer>> Solution(int[] nums) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> output = new ArrayList<Integer>();
for (int num : nums) {
output.add(num);
}
int n = nums.length;
premuteCore(n, output, res, 0);
return res;
}
//回溯算法
public void premuteCore(int n, List<Integer> output, List<List<Integer>> answ, int first) {
// 所有数都填完了
if (first == n) {
answ.add(new ArrayList<Integer>(output));
}
for (int i = first; i < n; i++) {
// 动态维护数组
Collections.swap(output, first, i);
// 继续递归填下一个数
premuteCore(n, output, answ, first + 1);
// 撤销操作
Collections.swap(output, first, i);
}
}
}