0%

Leetcode046-permutations

Description

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

Example

1
2
3
4
5
6
7
8
9
10
Input: [1,2,3]
Output:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

Solution

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
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) return res;

boolean[] visited = new boolean[nums.length];
helper(nums, res, new ArrayList<Integer>(), visited);

return res;
}

private void helper(int[] nums, List<List<Integer>> res, List<Integer> cur, boolean[] visited){
if (cur.size() == nums.length){
res.add(new ArrayList<Integer>(cur));
return;
}

for (int i = 0; i < nums.length; i++){
if (!visited[i]){
visited[i] = true;
cur.add(nums[i]);
helper(nums, res, cur, visited);
cur.remove(cur.size() - 1);
visited[i] = false;
}
}
}
}