55 lines
1.3 KiB
C++
55 lines
1.3 KiB
C++
|
/**
|
|||
|
* File: permutations_i.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> I */
|
|||
|
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>
|
|||
|
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>
|
|||
|
if (!selected[i]) {
|
|||
|
// <20><><EFBFBD>ԣ<EFBFBD><D4A3><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><EFBFBD><F1A3ACB8><EFBFBD>״̬
|
|||
|
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> I */
|
|||
|
vector<vector<int>> permutationsI(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, 2, 3};
|
|||
|
|
|||
|
vector<vector<int>> res = permutationsI(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;
|
|||
|
}
|