Leetcode 47 Solution

This article provides solution to leetcode question 47 (permutations-ii)

https://leetcode.com/problems/permutations-ii

Solution

class Solution {
public:
    void permute(vector<int>& nums, int k, vector<vector<int>>& res) {
        int n = nums.size();

        if (k == n)
        {
            res.push_back(nums);
            return;
        }

        set<int> doneNums;
        for (int i = k; i < n; i++)
        {
            if (doneNums.find(nums[i]) != doneNums.end())
                continue;

            swap(nums[i], nums[k]);
            permute(nums, k + 1, res);
            swap(nums[i], nums[k]);

            doneNums.insert(nums[i]);
        }
    }

    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> res;
        permute(nums, 0, res);
        return res;
    }
};