LeetCode | Permutations II
来源:互联网 发布:网络空间安全搜索引擎 编辑:程序博客网 时间:2024/06/09 18:11
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
have the following unique permutations:[1,1,2]
, [1,2,1]
, and [2,1,1]
.
带有重复数据的全排列。也是在上一题的基础上修改的,首先要对数据进行排列,然后再进行全排列求解。不然会很麻烦,甚至得不出结果。
我们交换的时候,让0位的值和后面的交换,有两种情况
第0位到第i位的数据都相等,则不用交换,继续向后找。
第0位和第i位的数据不相等,交换--求解--交换回来。再往下交换的时候,要判断是否和第i位相等,若相等则继续向后找,直到不相等的时候,再和第0位交换。
这就导致了上面两种情形之间起始为k(深层次函数的起始位置),不能交换。所有要特殊处理。i==k的时候,进行递归,不进行后面的判断。
代码如下:
void Permut(int arr[],int k,int n){ if(k == n){ //当所有值全遍历过了,就输出 Print(arr,n); return ; } int temp = arr[k]; //备份值,下次交换的和这次交换的不能一样。 for(int i = k;i < n;i++){ while(i!=k && i < n && temp == arr[i] ) //i==k的时候,忽略,当不能k的时候,才判断交换是否重复 ++i; if(i == n) return ; Swap(&arr[k],&arr[i]); Permut(arr,k+1,n); Swap(&arr[k],&arr[i]); temp = arr[i]; }}
0 0
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Leetcode: Permutations and Permutations II
- leetcode-permutations and permutations II
- Leetcode:Permutations与Permutations II
- LeetCode: Permutations II
- LeetCode Permutations II
- LeetCode: Permutations II
- [Leetcode] Permutations II
- [LeetCode] Permutations II
- [Leetcode] Permutations II
- leetcode Permutations II
- [LeetCode]Permutations II
- leetcode - Permutations II
- LeetCode-Permutations II
- [leetcode] Permutations II
- HDU1097 A hard puzzle
- Come on baby```!!!!
- Spring整合Struts2(接上篇,来自传智播客视频,包含所有源码)
- hdu 3836 Equivalent Sets(强连通分量--加边)
- java.util.Scanner应用详解
- LeetCode | Permutations II
- Android开发闪光灯-你的手机能闪亮嘛?
- 16进制颜色(html颜色值)字符串转为UIColor
- HDU4414 Finding crosses(模拟 || DFS)
- ssh框架+sitemesh编辑器上传图片被加载装饰器问题导致上传图片失败
- ##剑指offer 5.2 时间效率2 -最小的K个数
- java基础之反射(1.认识class类)
- hdu 1151 最小路径覆盖
- hdu 3832 Earth Hour (最短路变形)