Permutations I , II
来源:互联网 发布:淘宝网水晶家纺被子 编辑:程序博客网 时间:2024/06/05 14:25
Permutations
Given a collection of distinct numbers, return all possible permutations.
For example,[1,2,3]
have the following permutations:
[ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1]]
nums的每个数都与其后面的数交换,采用深度递归
void DFS(vector<int> & nums, int start, vector<vector<int>> & r)//注意这里是nums的引用传递
Permutations II
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], [2,1,1]]
https://discuss.leetcode.com/topic/8831/a-simple-c-solution-in-only-20-lines/47
先将数组排好序,然后进行元素交换,这里排重是个问题。如果采用递归时,将nums进行引用传递,第i个递归内的第i+1个递归会改变nums的值,
swap(nums, start, i);
permutating(ans, Arrays.copyOf(nums, nums.length), start+1);
swap(nums, start, i);
这样只是交换回来,是无法恢复原样的,也会有重复。
通过的代码:
void DFS(vector<vector<int>>& r,vector<int> nums,int start)//这里的nums是值传递。对于数组中的每个数如果前面没有与它重复的数,
那么它一定可以交换到当前迭代的首部,它后面的如果与他重复,就会被忽略,这样保证第i次迭代的首个元素不会有重复,然后再进行下一次迭代。
按照这里的值传递,举个例子,它的一次递归过程,发现下一次递归过程:它的后面3个元素也是排好序的
(1,2,2,3) (pos = 0, i = 0)
(2,1,2,3) (pos = 0, i = 1)
(2,1,2,3) (pos = 0, i =2) skipped, since array[0]=array[2]; //排重
(3,1,2,2) (pos = 0, i =3)
但按照引用传递的递归,它的后面3个元素不是排好序的(1,2,2,3) (pos = 0, i = 0)
(2,1,2,3) (pos = 0, i = 1)//1序列
(2,2,1,3) (pos = 0, i =2) //这回产生重复,下一次递归从pos=1开始,其子序列与上一个1序列产生的子序列一样
(3,2,2,1) (pos = 0, i =3)
如果排重的过滤条件为:if (nums[i] == nums[i - 1] && i != begin)也不行,排好序的队列,会在子递归的过程中失序,下次递归就无法排重了。另一种解法:增加一个数组used,用来表示第i个数是否在该次迭代中用过,每次选一个元素加入到存储排列的vector<int>中;
这里排重通过nums[i]和nums[j]是否相等及used来确定。
- LeetCode Permutations I && II
- [LeetCode][I]Permutations II
- leetcode: Permutations I II
- [LeetCode] Permutations I, II
- LeetCode | Permutations I,II
- Permutations I , II
- 46, 47 Permutations I, II
- Permutations I(II) 数组的全排列
- LeetCode题解:Permutations I and II
- [LeetCode 46 & 47]Permutations I & II
- <LeetCode OJ> 47/46 Permutations (II / I)
- LeetCode 46/47. Permutations i, ii
- [Leetcode] #46#47 Permutations I & II
- 【LeetCode】Permutations && Permutations II
- leetcode: Permutations/Permutations II
- leetcode Permutations & Permutations II
- [Leetcode]Permutations && Permutations II
- Permutations and Permutations II
- Android使用Application总结
- Codeforces 500B New Year Permutation(更换位置,找最小字典数)
- leetcode 15 3Sum
- Arch linux (虚拟机)安装教程
- HDU 5898 odd-even number (2016亚洲区沈阳站网络赛 )
- Permutations I , II
- Asp图片大小处理及AspJpeg失效设置
- 通过反射获取泛型类的类型
- 【java】面向对象——封装性、继承性和多态性
- Android帧缓冲区(Frame Buffer)硬件抽象层(HAL)模块Gralloc的实现原理分析
- 8CollapsingToolbarLayout源码分析
- poj 1789
- Java IO字符流读取文件总结
- JSP笔记