Permutations
LeetCode https://leetcode.cn/problems/permutations/
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
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> results = new ArrayList<>();
if (nums == null) {
return results;
}
if (nums.length == 0) {
results.add(new ArrayList<Integer>());
return results;
}
List<Integer> list = new ArrayList<>();
helper(nums, list, results);
return results;
}
private void helper(int[] nums,
List<Integer> permutation,
List<List<Integer>> results) {
if (permutation.size() == nums.length) {
results.add(new ArrayList<Integer>(permutation));
return;
}
for (int i = 0; i < nums.length; i++) {
if (permutation.contains(nums[i])) {
continue;
}
permutation.add(nums[i]);
helper(nums, permutation, results);
permutation.remove(permutation.size() - 1);
}
}
}
This post is licensed under CC BY 4.0 by the author.