LeetCode 46 : Permutations 问题描述
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>> result = new ArrayList<>();
if (nums == null || nums.length == 0)
return result;
boolean[] visited = new boolean[nums.length];
backtrace(nums, result, visited, new ArrayList<>());
return result;
}
private void backtrace(int[] nums, List<List<Integer>> result, boolean[] visited, ArrayList<Integer> temp) {
if (temp.size() == nums.length) {//结束条件
result.add(new ArrayList<>(temp));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i])
continue;// 元素访问过 跳过
visited[i] = true;
temp.add(nums[i]);
backtrace(nums, result, visited, temp);
temp.remove(temp.size() - 1);
visited[i] = false;
}
}
}
LeetCode 47: Permutations II问题描述
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
思路
在实现上,和 Permutations 不同的是要先排序,然后在添加一个元素时,判断这个元素是否等于前一个元素,如果等于,并且前一个元素还未访问,那么就跳过这个元素。重复元素只按顺序选择,若当前元素未被选择且前一元素与当前元素值相等也未被选择则跳过,这一可能情况与先选小序号后选大序号的相同元素相同
只需要判断i和i-1(而不需要判断i与i-2…) 相同的元素一定是相邻的,如果i-2,i-1,i相同,那么在上一轮循环就已经判断了i-1,i,本轮循环不需要重复判断
java实现
class Solution {
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0)
return result;
Arrays.sort(nums);
boolean[] visited = new boolean[nums.length];
backtrack(nums, visited, result, new ArrayList<>());
return result;
}
private void backtrack(int[] nums, boolean[] visited, List<List<Integer>> result, ArrayList<Integer> temp) {
if (temp.size() == nums.length) {
result.add(new ArrayList<>(temp));
return;
}
for (int i = 0; i < nums.length; i++) {
if (visited[i])
continue;
if (i != 0 && nums[i] == nums[i - 1] && !visited[i - 1])
continue;
visited[i] = true;
temp.add(nums[i]);
backtrack(nums, visited, result, temp);
temp.remove(temp.size() - 1);
visited[i] = false;
}
}
}