46 Permutations

1. Question

Given a collection of distinct numbers, return all possible permutations.
For example, [1,2,3]have the following permutations:
1
[
2
[1,2,3],
3
[1,3,2],
4
[2,1,3],
5
[2,3,1],
6
[3,1,2],
7
[3,2,1]
8
]
Copied!

2. Implementation

(1) Backtracking
1
class Solution {
2
public List<List<Integer>> permute(int[] nums) {
3
List<List<Integer>> res = new ArrayList<>();
4
List<Integer> permutation = new ArrayList<>();
5
boolean[] used = new boolean[nums.length];
6
getPermutations(nums, used, permutation, res);
7
return res;
8
}
9
10
public void getPermutations(int[] nums, boolean[] used, List<Integer> permutation, List<List<Integer>> res) {
11
if (permutation.size() == nums.length) {
12
res.add(new ArrayList<>(permutation));
13
return;
14
}
15
16
for (int i = 0; i < nums.length; i++) {
17
if (!used[i]) {
18
used[i] = true;
19
permutation.add(nums[i]);
20
getPermutations(nums, used, permutation, res);
21
permutation.remove(permutation.size() - 1);
22
used[i] = false;
23
}
24
}
25
}
26
}
Copied!

3. Time & Space Complexity

Backtracking: 时间复杂度O(n!), 空间复杂度O(n!)