# Permutations I & II

lpy1990

## Permutations I

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

Example:

Input: [1,2,3]
Output: [
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1] ]

### 代码

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

}
}``````

## Permutations II

### 代码

``````class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> res = new ArrayList<>();
if (nums == null || nums.length == 0) {
return res;
}
Arrays.sort(nums);
List<Integer> tmp = new ArrayList<>();
boolean[] visit = new boolean[nums.length];
dfs(nums, tmp, res, visit);
return res;
}

private void dfs(int[] nums, List<Integer> tmp, List<List<Integer>> res,  boolean[] visit) {
if (tmp.size() == nums.length) {
return;
}
for (int i =0; i < nums.length; i++) {
if (visit[i]) {
continue;
}
if (i != 0 && nums[i] == nums[i-1] && visit[i-1] == false) {
continue;
}
visit[i] = true;
dfs(nums, tmp, res, visit);
tmp.remove(tmp.size() - 1);
visit[i] = false;
}

}
}``````

26 声望
10 粉丝
0 条评论