leetcode---permutations-ii---dfs

来源:互联网 发布:返利 知乎 编辑:程序博客网 时间:2024/05/21 22:42

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].

class Solution {public:    bool ok(int i, int j, vector<int> &num)    {        for(int k=i; k<j; k++)        {            if(num[k] == num[j])                return false;        }        return true;    }    void dfs(int dep, int n, vector<vector<int>> &ans, vector<int> &num)    {        if(dep >= n)        {            ans.push_back(num);        }        for(int i=dep; i<n; i++)        {            if(ok(dep, i, num))            {                swap(num[i], num[dep]);                dfs(dep+1, n, ans, num);                swap(num[i], num[dep]);            }        }    }    vector<vector<int> > permuteUnique(vector<int> &num)     {        vector<vector<int>> ans;        int n = num.size();        if(n == 0)            return ans;        dfs(0, n, ans, num);        return ans;    }};