cpp-algo-cases/chapter_backtracking/permutations_ii.cpp

57 lines
1.5 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: permutations_ii.cpp
* Created Time: 2023-04-24
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E3B7A8>ȫ<EFBFBD><C8AB><EFBFBD><EFBFBD> II */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
// <20><>״̬<D7B4><CCAC><EFBFBD>ȵ<EFBFBD><C8B5><EFBFBD>Ԫ<EFBFBD><D4AA><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ʱ<EFBFBD><CAB1><EFBFBD><EFBFBD>¼<EFBFBD><C2BC>
if (state.size() == choices.size()) {
res.push_back(state);
return;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>
unordered_set<int> duplicated;
for (int i = 0; i < choices.size(); i++) {
int choice = choices[i];
// <20><>֦<EFBFBD><D6A6><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ظ<EFBFBD>ѡ<EFBFBD><D1A1>Ԫ<EFBFBD><D4AA> <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ظ<EFBFBD>ѡ<EFBFBD><D1A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>
if (!selected[i] && duplicated.find(choice) == duplicated.end()) {
// <20><><EFBFBD>ԣ<EFBFBD><D4A3><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD>񣬸<EFBFBD><F1A3ACB8><EFBFBD>״̬
duplicated.emplace(choice); // <20><>¼ѡ<C2BC><D1A1><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ԫ<EFBFBD><D4AA>ֵ
selected[i] = true;
state.push_back(choice);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB>ѡ<EFBFBD><D1A1>
backtrack(state, choices, selected, res);
// <20><><EFBFBD>ˣ<EFBFBD><CBA3><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD>񣬻ָ<F1A3ACBB><D6B8><EFBFBD>֮ǰ<D6AE><C7B0>״̬
selected[i] = false;
state.pop_back();
}
}
}
/* ȫ<><C8AB><EFBFBD><EFBFBD> II */
vector<vector<int>> permutationsII(vector<int> nums) {
vector<int> state;
vector<bool> selected(nums.size(), false);
vector<vector<int>> res;
backtrack(state, nums, selected, res);
return res;
}
/* Driver Code */
int main() {
vector<int> nums = {1, 1, 2};
vector<vector<int>> res = permutationsII(nums);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> nums = ";
printVector(nums);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> res = ";
printVectorMatrix(res);
return 0;
}