C++ DFS solution ,23ms, beat 98.58%


  • 0
    T

    class Solution {
    public:
    void myDFS(vector<int>& nums, vector<vector<int>>& result, vector<int>& sub,vector<int>&used, int index)
    {
    if(sub.size()==nums.size())
    {
    result.push_back(sub);
    return;
    }
    for(int i = 0; i < nums.size(); ++i)
    {
    if(!used[i] && (i==0 || nums[i]!=nums[i-1] || used[i-1]))
    {
    sub.push_back(nums[i]);
    used[i]=1;
    myDFS(nums,result,sub,used,index+1);
    used[i]=0;
    sub.pop_back();

            }
        }
    }
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> result;
        vector<int> sub;
        sort(nums.begin(), nums.end());
        vector<int> used(nums.size(),0);
        int index = 0;
        myDFS(nums, result, sub, used, index);
        return result;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.