LeetCode 47. 全排列 II(Permutations II)

题目描述

 

给定一个可包含重复数字的序列,返回所有不重复的全排列。

示例:

输入: [1,1,2]
输出:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

 

解题思路

 

类似于LeetCode46.全排列,只不过对于每个起始位置维护一个之前遍历过的数集,在交换时判断当前数是否在数集中出现,若出现过则不能交换此数,否则与起始位置交换并将此数加入到数集中。

 

代码

 

 1 class Solution {
 2 public:
 3     vector<vector<int>> permuteUnique(vector<int>& nums) {
 4         vector<vector<int>> res;
 5         pmt(nums, 0, res);
 6         return res;
 7     }
 8     void pmt(vector<int> &seq, int idx, vector<vector<int>> &res){
 9         if(idx == seq.size() - 1)
10             res.push_back(seq);
11         else{
12             vector<int> pre;
13             for(int i = idx; i < seq.size(); i++){
14                 vector<int>::iterator iter = find(pre.begin(), pre.end(), seq[i]);
15                 if(iter != pre.end()) continue;
16                 swap(seq[idx], seq[i]);
17                 pmt(seq, idx + 1, res);
18                 swap(seq[i], seq[idx]);
19                 pre.push_back(seq[i]);
20             }
21         }
22     }
23 };

 

posted @ 2018-07-31 15:53  FlyingWarrior  阅读(127)  评论(0编辑  收藏  举报