回溯Leetcode 47 Permutations II
阿新 • • 發佈:2018-12-28
Leetcode 47
Permutations II
- Problem Description:
經典回溯問題:重複數字的全排列
具體的題目資訊:
https://leetcode.com/problems/permutations-ii/description/ - Example:
- Solution:
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;
}
}
}
};