题目:
回溯:排列(元素可重不可复选)
重复则需要先Arrays.sort 排序;
排列问题的输⼊如果存在重复,需要在选择时限制限制两个重复元素的相对位置 !
当if(i>0 && nums[i]==nums[i-1] && onPath[i-1])==false
则continue !
由于是排列而不是子集,遍历到叶子节点才会将path添加res;
Java实现:
class Solution {
boolean[] onPath;
List<List<Integer>> res=new LinkedList<>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
//有重复得先排序!
Arrays.sort(nums);
//排列用onPath来记录遍历情况
onPath=new boolean[nums.length];
dfs(nums);
return res;
}
void dfs(int[] nums){
//终止条件
if(path.size()==nums.length){
res.add(new LinkedList(path));
return;
}
//组合/子集才用start来作为终止条件
for(int i =0;i<nums.length;i++){
//选择
if(onPath[i]){ //跳过已遍历的
continue;
}
// 固定相同元素在排列中的位置 ※※※
if(i>0 && nums[i]==nums[i-1] && onPath[i-1]==false){
continue;
}
path.add(nums[i]);
onPath[i]=true;
dfs(nums);
//撤销
path.removeLast();
onPath[i]=false;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/89252.html