#Leetcode# 47. Permutations II

Posted 丧心病狂工科女

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#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$ 去重 然后就是普通的全排列啦!

以上是关于#Leetcode# 47. Permutations II的主要内容,如果未能解决你的问题,请参考以下文章

leetcode-47

LeetCode:全排列II47

#Leetcode# 47. Permutations II

leetcode 47. 全排列 II

LeetCode 47

LeetCode46,47 Permutations, Permutations II