Leetcode47:全排列II
-
知识前提:以leetcode46全排列为基础
-
题目:
- 给定一个可包含重复数字的序列
nums
,按任意顺序 返回所有不重复的全排列。
- 给定一个可包含重复数字的序列
-
思路:在全排列(leetcode46题的基础上进行去重)
-
去重最为关键的代码为:(树层相同元素进行去重)
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) { continue; }
-
-
代码如下:
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
Boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums.length==0){
res.add(new ArrayList<>(path));
return res;
}
used = new Boolean[nums.length];
Arrays.sort(nums);
Arrays.fill(used,false);
backTrack(nums,used);
return res;
}
void backTrack( int[] nums, Boolean[] used ) {
if ( nums.length == path.size() ) {
res.add(new ArrayList<>(path));
return;
}
for ( int i = 0; i < nums.length; i++ ) {
//同一树层相同元素进行去重
if ( i > 0 && nums[i-1] == nums[i] && used[i-1] == false ){
continue;
}
if ( used[i] == false ) {
used[i]=true;
path.add(nums[i]);
backTrack(nums, used);
path.remove(path.size() - 1);
used[i]=false;
}
}
}
}