[Leetcode] Permutations II
2014-11-06 14:05
357 查看
题目:
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,
思路:重点在如何避免冗余。比较trivial的一个做法是结果都放到set中,但是需要额外空间。观察题目中的例子可以看出冗余是如何形成的,对于第一个1,和自己swap后的结果为 1 1 2,按照Permuation I的做法,接下来和第二个1 swap,产生冗余结果。再看一个例子:[1, 2, 2]. 当1和第一个2 swap后,结果为 2 1 2,此时1再和后面的2 swap,产生 2 2 1. 但是,在
1 2 2 这步,如果1和第二个2直接swap,产生的结果还是 2 2 1,造成冗余。因此可以看到一个一般情况,对于数组AAAAAABBBBBBCCCCCC,假设当前位置为A,现在开始跟C交换,可以看到:A只需要跟第一个C交换,便可以产生和后面C交换同样的效果。换言之,每次需要交换的,从该元素开始,所有第一次出现的元素。需要注意的是,虽然之前做了排序,但数组在递归的过程中是乱序的,例如CAAAAABBBBBBACCCCC,当前元素为B. 因此不能通过 while (num[i] == num[i+1]) i++;
这样的简单方式判断,因为重复出现的元素可能不连续。
总结:复杂度为O(n!).
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].
思路:重点在如何避免冗余。比较trivial的一个做法是结果都放到set中,但是需要额外空间。观察题目中的例子可以看出冗余是如何形成的,对于第一个1,和自己swap后的结果为 1 1 2,按照Permuation I的做法,接下来和第二个1 swap,产生冗余结果。再看一个例子:[1, 2, 2]. 当1和第一个2 swap后,结果为 2 1 2,此时1再和后面的2 swap,产生 2 2 1. 但是,在
1 2 2 这步,如果1和第二个2直接swap,产生的结果还是 2 2 1,造成冗余。因此可以看到一个一般情况,对于数组AAAAAABBBBBBCCCCCC,假设当前位置为A,现在开始跟C交换,可以看到:A只需要跟第一个C交换,便可以产生和后面C交换同样的效果。换言之,每次需要交换的,从该元素开始,所有第一次出现的元素。需要注意的是,虽然之前做了排序,但数组在递归的过程中是乱序的,例如CAAAAABBBBBBACCCCC,当前元素为B. 因此不能通过 while (num[i] == num[i+1]) i++;
这样的简单方式判断,因为重复出现的元素可能不连续。
class Solution { public: void swap(int& a, int& b) { int temp = a; a = b; b = temp; } bool can_swap(const vector<int>& num, int start, int end) { //check duplicates for (; start < end; ++start) { if (num[start] == num[end]) return false; } return true; } void permute_helper(vector<int>& num, int pos, vector<vector<int>>& result) { if (pos == (int)num.size()) { //reach the end result.push_back(num); return; } for (int i = pos; i < (int)num.size(); ++i) { if (can_swap(num, pos, i)) { swap(num[pos], num[i]); permute_helper(num, pos + 1, result); swap(num[pos], num[i]); } } } vector<vector<int> > permuteUnique(vector<int> &num) { sort(num.begin(), num.end()); vector<vector<int>> result; permute_helper(num, 0, result); return result; } };
总结:复杂度为O(n!).
相关文章推荐
- [LeetCode] Permutations II
- leetcode_middle_93_47. Permutations II
- LeetCode 47 Permutations II
- [LeetCode] Permutations II
- [LeetCode 题解]: Permutations II
- [LeetCode]Permutations II
- [Leetcode] Permutations II
- [leetcode] Permutations II
- LeetCode:Permutations, Permutations II(求全排列)
- leetcode 47 : Permutations II
- leetcode-47-Permutations II 搜索-剪枝
- [LeetCode] Permutations II
- [LeetCode] Permutations II
- Permutations II(leetcode)
- leetcode - Permutations II
- Leetcode 47 Permutations II
- LeetCode-47-Permutations II 递归+dict
- [LeetCode] Permutations II
- LeetCode 47. Permutations II
- <LeetCode OJ> 47. Permutations II