# Permutations I & II leetcode

lpy1990

## Permutations I

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

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

### 回溯法

#### 代码

``````public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> res= new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
return res;
}
List<Integer> tem = new ArrayList<Integer>();
Arrays.sort(nums);
boolean[] visit = new boolean[nums.length];
helper(nums, visit, res, tem);
return res;
}
public void helper(int[] nums, boolean[] visit, List<List<Integer>> res, List<Integer> tem) {
if (tem.size() == nums.length) {
return;
}
for (int i = 0; i < nums.length; i++) {
if (visit[i] == true) {
continue;
}
visit[i] = true;
helper(nums, visit, res, tem);
tem.remove(tem.size() - 1);
visit[i] = false;
}
}``````

## Permutations II

Given a collection of numbers that might contain duplicates, return
all possible unique permutations.

For example, [1,1,2] have the following unique permutations: [1,1,2],
[1,2,1], and [2,1,1].

### 回溯法

#### 代码

``````public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res= new ArrayList<List<Integer>>();
if (nums == null || nums.length == 0) {
return res;
}
List<Integer> tem = new ArrayList<Integer>();
Arrays.sort(nums);
boolean[] visit = new boolean[nums.length];
helper(nums, visit, res, tem);
return res;
}
public void helper(int[] nums, boolean[] visit, List<List<Integer>> res, List<Integer> tem) {
if (tem.size() == nums.length) {
return;
}
for (int i = 0; i < nums.length; i++) {
if (visit[i] == true) {
continue;
}
if (i != 0 && nums[i] == nums[i - 1] && !visit[i - 1]) {
continue;
}
visit[i] = true;