当前位置:网站首页>全排列II[存在相同元素去重 + 标准回溯]
全排列II[存在相同元素去重 + 标准回溯]
2022-06-24 21:17:00 【REN_林森】
前言
对于全排列问题,一般采用DFS进行枚举(标准回溯),而当数组中出现重复元素时,就会枚举出重复的集合。
如何去重,把相等的元素靠在一起(可排序),然后通过pre和cur是否相同,从而来去重。
一、全排列II

二、把元素靠在一起 + 标准回溯
package everyday.medium;
import java.util.*;
// 全排列II
public class PermuteUnique {
public List<List<Integer>> permuteUnique(int[] nums) {
// 先排序,让连续的数字放在相邻处,才好配合pre来去重。
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<>();
List<Integer> el = new ArrayList<>();
// Set 记录哪些数字已经被用了。
Set<Integer> set = new HashSet<>();
// dfs搜索方式取全排列。
dfs(nums, el, ans, set);
// 返回dfs后填充好的list
return ans;
}
private void dfs(int[] nums, List<Integer> el, List<List<Integer>> ans, Set<Integer> set) {
// 当每个元素都被选择,拿去排列了,则添加该排列到list中。
if (el.size() == nums.length) {
ans.add(new ArrayList<>(el));
return;
}
// 标准回溯
// 去重,当在该位置上选择不同的两个数,而这两个数相等时,产生重复。
int pre = 1 << 31;
for (int i = 0; i < nums.length; i++) {
// 当前后选择的两个元素一样 | 这个元素已经被选了,则过。
if (pre == nums[i] || set.contains(i)) continue;
// 标准回溯
el.add(nums[i]);
set.add(i);
dfs(nums, el, ans, set);
set.remove(i);
el.remove(el.size() - 1);
// 更新pre为当前选择的元素,为下面的选择做准备。
pre = nums[i];
}
}
}
总结
1)标准回溯
2)通过把元素靠在一起,再配合pre 和 cur 变量是否相等来达到去重的目的。
参考文献
[1] LeetCode 全排列II
边栏推荐
- Boutique enterprise class powerbi application pipeline deployment
- 数组中关于sizeof()和strlen
- Novice, let me show you the "soft test" at one time
- Lenovo tongfuyao: 11 times the general trend, we attacked the city and pulled out the stronghold all the way
- Tianshu night reading notes -- disassembly engine xde32
- PHP easywechat and applet realize long-term subscription message push
- 归并排序求逆序数
- mysql查询时间戳转换成日期格式
- 【实用系列】家内wifi全覆盖
- Ideas and examples of divide and conquer
猜你喜欢

4年工作经验,多线程间的5种通信方式都说不出来,你敢信?

2种常见的设备稼动率OEE监测方法

"One good programmer is worth five ordinary programmers!"

修身励学篇

Programmer: did you spend all your savings to buy a house in Shenzhen? Or return to Changsha to live a "surplus" life?

Deploy a production cluster using Loki microservice pattern

Fan benefits, JVM manual (including PDF)

Linux64Bit下安装MySQL5.6-不能修改root密码

Heavyweight: the domestic ide was released, developed by Alibaba, and is completely open source! (high performance + high customization)

Bi SQL alias
随机推荐
“一个优秀程序员可抵五个普通程序员!”
Novice, let me show you the "soft test" at one time
Redis persistence
C语言边界计算和不对称边界
Abnova丨A4GNT多克隆抗体中英文说明
The optimism about technology is making Dell achieve more than expected
实验5 8254定时/计数器应用实验【微机原理】【实验】
Which securities company should I choose to open an account online? Is it safe to open an account online?
Boutique enterprise class powerbi application pipeline deployment
ImageView shows network pictures
Abnova丨CSV 磁珠中英文说明
Cobalt strike installation tutorial
C language boundary calculation and asymmetric boundary
戴尔为何一直拒绝将商用本的超薄推向极致?
Tencent cloud wecity Hello 2022!
Convolution and transpose convolution
国内炒股开户正规安全的具体名单
Tencent cloud wecity solution
js数组对象转对象
VB 学习笔记