Star

LeetCode 46.Permutations

Quesiton

Given a collection of distinct numbers, return all possible permutations.

For example, [1,2,3] have the following permutations:

1
2
3
4
5
6
7
8
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

Explanation

这道题是排列组合问题,所以用DFS和回溯法递归。注意长度要和原来的数组长度相等。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
helper(nums, new ArrayList<Integer>(), result);
return result;
}
public void helper(int[] nums, List<Integer> list, List<List<Integer>> result) {
if (list.size() == nums.length) {
result.add(new ArrayList<Integer>(list));
return;
}
for (int i=0; i<nums.length; i++) {
if (list.contains(nums[i])) continue;
list.add(nums[i]);
helper(nums, list, result);
list.remove(list.size()-1);
}
}
}