#Leetcode# 47. Permutations II

https://leetcode.com/problems/permutations-ii/

 

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

代码:

class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        int n = nums.size();
        vector<int> vis(n, 0);
        vector<int> v;
        set<vector<int>> ans;
        
        dfs(nums, 0, vis, v, ans);
        return vector<vector<int>>(ans.begin(), ans.end());
    }
    void dfs(vector<int>& nums, int step, vector<int>& vis, vector<int>& v, set<vector<int>>& ans) {
        if(step == nums.size()) 
            ans.insert(v);
        
        for(int i = 0; i < nums.size(); i ++) {
            if(vis[i] == 0) {
                vis[i] = 1;
                v.push_back(nums[i]);
                dfs(nums, step + 1, vis, v, ans);
                v.pop_back();
                vis[i] = 0;
            }
        }
    }
};

 要用到 $set$ 去重 然后就是普通的全排列啦!

posted @ 2018-11-23 18:25  丧心病狂工科女  阅读(142)  评论(0编辑  收藏  举报