1. 程式人生 > >回溯Leetcode 47 Permutations II

回溯Leetcode 47 Permutations II

Leetcode 47

Permutations II

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