# 47. Permutations II (Medium)

## 1.問題&#x20;

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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHx7z8LhEk2sxMCHPDw%2F-LHxDdp-UCKquqQIsW07%2F201872105.jpg?alt=media\&token=4f9421be-0a99-4966-9217-fc7483362012)

## 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

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHx7z8LhEk2sxMCHPDw%2F-LHxETIfDB_fwhu0B8eq%2F201872106.jpg?alt=media\&token=7564a668-668a-4c84-a0b8-bad8cf838cfb)
