Leetcode 47. Permutations II
来源:互联网 发布:mac照片占用空间 编辑:程序博客网 时间:2024/06/02 17:06
题意
生成一个数组的全排列,去除重复的排列数组
题解
用递归实现。每个位置的数字都能和它后面的所有数字交换的,一共有n!种。
用set去重超时,需要在递归中剪枝。如果交换中两个数的中间有一个数和后面的交换数相同(说明前面的循环中已经生成过此种排列),则停止生成此种排列。
代码
class Solution {public: vector<vector<int> > result; bool canSwap(vector<int> &nums, int begin, int end) { for(int i = begin; i < end; i++) { if(nums[i] == nums[end]) return false; } return true; } void gen_permutation(int pos, vector<int> &nums) { if(pos == nums.size()) { result.push_back(nums); } else { for(int i = pos; i < nums.size(); i++) { if(canSwap(nums, pos, i))//// if previsous loop hasn't this permutation that start with nums[pos] { swap(nums[i], nums[pos]); gen_permutation(pos + 1, nums); swap(nums[i], nums[pos]); } } } } vector<vector<int> > permuteUnique(vector<int>& nums) { gen_permutation(0, nums); return result; }};
0 0
- [LeetCode]47.Permutations II
- LeetCode 47.Permutations II
- LeetCode --- 47. Permutations II
- [Leetcode] 47. Permutations II
- [leetcode] 47.Permutations II
- LeetCode 47. Permutations II
- 47. Permutations II LeetCode
- Leetcode 47. Permutations II
- LeetCode 47. Permutations II
- LeetCode - 47. Permutations II
- [LeetCode] 47. Permutations II
- leetcode 47. Permutations II
- [LeetCode]--47. Permutations II
- [LeetCode]--47. Permutations II
- [leetcode] 47. Permutations II
- leetcode 47. Permutations II
- Leetcode-47. Permutations II
- [LeetCode]--47. Permutations II
- Hrbust1658一笔画
- 星号图
- HDU 2063 过山车 (二分匹配 -匈牙利算法)
- hdu 1695 莫比乌斯反演
- uva10128(Queue)
- Leetcode 47. Permutations II
- pat乙级总结
- Centos下本地连接postgresql时出现认证错误的问题
- 鼠标移入/移出改变图片透明度_jQuery效果
- 一起talk C栗子吧(第一百三十二回:C语言实例--从内存的角度看进程和线程)
- 第五周项目1 三角形类的练习(5)
- leetcode 74. Search a 2D Matrix
- 《JAVA夜未眠》读感
- C++ 设计模式 —— 访问者(Visitor)