# 47. Permutations II (Medium)

## 1.問題&#x20;

* 給予一個重複數字的集合, 回傳所有可能的排列組合

![](/files/-LHxDdp-UCKquqQIsW07)

## 2.想法&#x20;

* Recursive + back tracking
* 與46.Permutations相同, 但是如果傳入的是重覆的數字則不加入排列而且數列必須先排序&#x20;

## 3.程式碼

```
class Solution {
public:
    vector<vector<int>> permuteUnique(vector<int>& nums) {
        vector<vector<int>> res;
        vector<int> record;
        vector<bool> used(nums.size(), false);
        sort(nums.begin(), nums.end());
        helper(res, nums, record, used);
        return res;
    }
private:
    void helper(vector<vector<int>>& res, vector<int>& nums, vector<int>& record, vector<bool>& used) {
        if (record.size() == nums.size()) {
            res.push_back(record);
            return;
        }
        for (int i = 0 ; i < nums.size(); i++) {
            if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
                continue;
            }
            if (!used[i]) {
                used[i] = true;
                record.push_back(nums[i]);
                helper(res, nums, record, used);
                record.pop_back();
                used[i] = false;
            }
        }
    }
};
```

## 4.Performance

![](/files/-LHxETIfDB_fwhu0B8eq)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/47.-permutations-ii-medium.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
