leetcode---Permutations II

来源:互联网 发布:cool edit for mac版 编辑:程序博客网 时间:2024/05/19 23:01

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:    vector<vector<int>> ans;    vector<int> tmp;    bool canSwap(int i, int j, vector<int>& nums)    {        for(int k=i; k<j; k++)            if(nums[k] == nums[j])                return false;        return true;    }    void dfs(int depth, vector<int>& nums)    {        if(depth >= nums.size()-1)        {            tmp.clear();            for(int i=0; i<nums.size(); i++)                tmp.push_back(nums[i]);            ans.push_back(tmp);            return;        }        for(int i=depth; i<nums.size(); i++)        {            if(canSwap(depth, i, nums))            {                swap(nums[depth], nums[i]);                dfs(depth+1, nums);                swap(nums[depth], nums[i]);            }        }    }    vector<vector<int>> permuteUnique(vector<int>& nums)     {        dfs(0, nums);        return ans;    }};
0 0
原创粉丝点击