代码改变世界

leetcode - Permutations II

2013-11-10 10:20  张汉生  阅读(132)  评论(0编辑  收藏  举报

 

 1 class Solution {
 2 public:
 3     vector<vector<int> > permuteUnique(vector<int> &num) {
 4         // IMPORTANT: Please reset any member data you declared, as
 5         // the same Solution instance will be reused for each test case.
 6         sort(num.begin(),num.end());
 7         vector<vector<int>> rlt;
 8         rlt.push_back(num);
 9         int n = num.size();
10         while (true){
11             int i;
12             for (i=n-2; i>=0; i--){
13                 if (num[i]<num[i+1])
14                     break;
15             }
16             if (i<0)
17                 break;
18             int min = num[i+1];
19             int minIndex = i+1;
20             for (int j =i+1+1; j<n; j++){
21                 if (num[j]>num[i] && num[j]<min){
22                     min = num[j];
23                     minIndex = j;
24                 }
25             }
26             int tmp = num[i];
27             num[i] = num[minIndex];
28             num[minIndex] = tmp;
29             sort(&num[i+1], &num[n]);
30             rlt.push_back(num);
31         }
32         return rlt;
33     }
34 };