Permutations 中不带有重复元素
Permutations II 中带有重复元素
Permutations
java
public class Solution {
/*
* @param nums: A list of integers.
* @return: A list of permutations.
*/
public List<List<Integer>> permute(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
result.add(new ArrayList<Integer>());
return result;
}
List<Integer> path = new ArrayList<>();
Set<Integer> set = new HashSet<>();
dfs(nums, path, result, set);
return result;
}
private void dfs(int[] nums,
List<Integer> path,
List<List<Integer>> result,
Set<Integer> set) {
if (path.size() == nums.length) {
result.add(new ArrayList<Integer>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (!set.contains(nums[i])) {
set.add(nums[i]);
path.add(nums[i]);
dfs(nums, path, result, set);
set.remove(nums[i]);
path.remove(path.size() - 1);
}
}
}
}
Permutations II
java
public class Solution {
/*
* @param : A list of integers
* @return: A list of unique permutations
*/
public List<List<Integer>> permuteUnique(int[] nums) {
// write your code here
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
result.add(new ArrayList<Integer>());
return result;
}
List<Integer> path = new ArrayList<>();
boolean[] visit = new boolean[nums.length];
Arrays.sort(nums);
dfs(nums, path, result, visit);
return result;
}
private void dfs(int[] nums,
List<Integer> path,
List<List<Integer>> result,
boolean[] visit) {
if (path.size() == nums.length) {
result.add(new ArrayList<Integer>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if ((visit[i] == true) || (i != 0 && nums[i] == nums[i - 1] && visit[i - 1] == false)) {
continue;
} else {
path.add(nums[i]);
visit[i] = true;
dfs(nums, path, result, visit);
visit[i] = false;
path.remove(path.size() - 1);
}
}
}
}