47. Permutations II

题目链接

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

解题思路

dfs的时候每一层上的数字不要重复出现

代码

class Solution {
public:
    void dfs(vector> &ans, vector &nums, int ind) {
        if (ind >= nums.size()) {
            ans.push_back(nums);
        }

        unordered_set set;
        for (int i = ind; i < nums.size(); ++i) {
            if (set.find(nums[i]) == set.end()) {
                set.insert(nums[i]);
                swap(nums[ind], nums[i]);
                dfs(ans, nums, ind + 1);
                swap(nums[ind], nums[i]);
            }
        }
    }

    vector> permuteUnique(vector& nums) {
        vector> ans;
        dfs(ans, nums, 0);
        return ans;
    }
};

你可能感兴趣的:(47. Permutations II)