Leetcode: Permutations II
来源:互联网 发布:mysql count if语句 编辑:程序博客网 时间:2024/05/12 19:53
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]
.
在I的基础上需要去掉重复出现的。
class Solution {public: vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > result; permuteUtil(result, num, 0, num.size() - 1); return result; } void permuteUtil(vector<vector<int> > &result, vector<int> &num, int start, int end) { if (start == end) { result.push_back(num); } else { for (int i = start; i <= end; ++i) { if (!isDuplicate(num, start, i)) { swap(num, start, i); permuteUtil(result, num, start + 1, end); swap(num, start, i); } } } } bool isDuplicate(vector<int> &num, int start, int target) { for (int i = start; i < target; ++i) { if (num[i] == num[target]) { return true; } } return false; } void swap(vector<int> &num, int i, int j) { int tmp = num[i]; num[i] = num[j]; num[j] = tmp; }};
=============================
对应的另外一种解法,关键是如果两个数重复,只有前一个数使用了才能使用后一个数。
class Solution {public: vector<vector<int> > permuteUnique(vector<int> &num) { vector<vector<int> > result; sort(num.begin(), num.end()); vector<bool> used(num.size(), false); vector<int> perm; permuteUtil(result, perm, num, used); return result; } void permuteUtil(vector<vector<int> > &result, vector<int> & perm, const vector<int> &num, vector<bool> &used) { if (perm.size() == num.size()) { result.push_back(perm); return; } for (int i = 0; i < num.size(); ++i) { if (used[i] || i > 0 && num[i] == num[i-1] && !used[i-1]) { continue; } used[i] = true; perm.push_back(num[i]); permuteUtil(result, perm, num, used); perm.pop_back(); used[i] = false; } }};在
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
- 开博记录
- Flex样式-Accordion篇
- 带你走进EJB--事务管理(2)
- hdu 1278
- vimrc
- Leetcode: Permutations II
- 2013年的总结和2014年规划
- 为JSplitPane的分隔条添加监视器
- OpenStack Cinder源码分析之一
- 给自己的新的一年的建议
- Gentoo firefox 安装 flash
- 大数据存取的选择:行存储还是列存储?
- Mysql设置远程
- ubuntu关于aptitude和apt-get