Easy c++ solution using backtracking


  • 0
    I
    class Solution {
    public:
        vector<vector<int> > permuteUnique(vector<int>& nums) {
            sort(nums.begin(), nums.end());
            vector<int> current;
            vector<vector<int> > ans;
            backtracking(ans, nums, current);
            return ans;
    
    
        }
    
        void backtracking(vector<vector<int> >& ans, vector<int>& nums, vector<int>& current) {
            if(nums.size() == 0) {
                ans.push_back(vector<int>(current));
                return;
            }
            for(int i = 0; i < nums.size(); i++) {
                if(i > 0 && nums[i] == nums[i-1]) continue;
                int tmp = nums[i];
                nums.erase(nums.begin() + i);
                current.push_back(tmp);
                backtracking(ans, nums, current);
                nums.insert(nums.begin() + i, tmp);
                current.pop_back();
            }
        }
    
    };
    

Log in to reply
 

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