leetcode: Permutations II

http://oj.leetcode.com/problems/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], and [2,1,1].

思路

如果前面Permutations的问题已经解决了的话,这个问题就变得非常简单。先排个序,以[1, 1, 2]为例,第一个1处理过以后,第二个1就可以跳掉了。

 1 class Solution {
 2 public:
 3     void internalpermuteUnique(vector<int> &num, int index, vector<int> &perm, vector<vector<int> > &result) {
 4         int size = num.size();
 5         
 6         if (size == index) {
 7             result.push_back(perm);
 8         }
 9         else {
10             for (int i = index; i < size; ++i) {
11                 if ((i > index) && (num[i] == num[index])) {
12                   continue;
13                 }
14                 else {
15                   swap(num[index], num[i]);
16                 }
17                 
18                 perm.push_back(num[index]);
19                 internalpermuteUnique(num, index + 1, perm, result);
20                 perm.pop_back();
21             }
22             
23             sort(num.begin() + index, num.end());
24         }
25     }
26     
27     vector<vector<int> > permuteUnique(vector<int> &num) {
28         vector<vector<int> > result;
29         vector<int> perm;
30         
31         sort(num.begin(), num.end());
32         internalpermuteUnique(num, 0, perm, result);
33         
34         return result;
35     }
36 };

 

posted @ 2013-11-14 14:58  移山测试工作室黑灯老师  阅读(1574)  评论(1编辑  收藏  举报
count website visits
Buy Computers