Easy understand, different from other solution


  • 0
    F

    This idea is very easy, don't have to sort, just add a hash on answer of https://leetcode.com/problems/permutations

    class Solution {
    private:
        void permuteHelp(vector<vector<int>> &r, vector<int> &nums, int k) {
            if (k >= nums.size() - 1) {
                r.push_back(nums);
                return;
            }
            unordered_map<int, bool> m;
            for (int i = k; i < nums.size(); ++i) {
                if (m[nums[i]])
                    continue;
                m[nums[i]] = true;
                swap(nums[k], nums[i]);
                permuteHelp(r, nums, k+1);
                swap(nums[k], nums[i]);
            }
        }
    public:
        vector<vector<int>> permuteUnique(vector<int>& nums) {
            vector<vector<int>> r;
            permuteHelp(r, nums, 0);
            return r;
        }
    };
    

Log in to reply
 

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