-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray46.java
More file actions
68 lines (64 loc) · 1.91 KB
/
Array46.java
File metadata and controls
68 lines (64 loc) · 1.91 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
64
65
66
67
68
package array;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @ProjectName: leetcode
* @Package: array
* @ClassName: Array46
* @Author: markey
* @Description:46. 全排列
* 给定一个 没有重复 数字的序列,返回其所有可能的全排列。
*
* 示例:
*
* 输入: [1,2,3]
* 输出:
* [
* [1,2,3],
* [1,3,2],
* [2,1,3],
* [2,3,1],
* [3,1,2],
* [3,2,1]
* ]
*
* 来源:力扣(LeetCode)
* 链接:https://leetcode-cn.com/problems/permutations
* 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
* @Date: 2020/4/25 22:41
* @Version: 1.0
*/
public class Array46 {
List<List<Integer>> res = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
List<Integer> numList = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
numList.add(nums[i]);
}
permute(new ArrayList<>(), numList);
return res;
}
public void permute(List<List<Integer>> base, List<Integer> nums) {
for (int i = 0; i < nums.size(); i++) {
List<List<Integer>> tempBase = new ArrayList<>(base);
List<Integer> tempNums = new ArrayList<>(nums);
if (tempBase.size() == 0) {
List<Integer> newList = new ArrayList<>();
newList.add(tempNums.get(i));
tempBase.add(newList);
} else {
for (int j = 0; j < tempBase.size(); j++) {
tempBase.get(j).add(tempNums.get(i));
tempNums.remove(i);
if (tempNums.size() == 0) {
System.out.println(base + " " + nums);
this.res.addAll(tempBase);
} else {
permute(tempBase, tempNums);
}
}
}
}
}
}