Files
hello-algo/ru/codes/cpp/chapter_backtracking/permutations_i.cpp
Yudong Jin 772183705e Add ru version (#1865)
* Add Russian docs site baseline

* Add Russian localized codebase

* Polish Russian code wording

* Update ru code translation.

* Update code translation and chapter covers.

* Fix pythontutor extraction.

* Add README and landing page.

* placeholder of profiles

* Use figures of English version

* Remove chapter paperbook
2026-03-28 04:24:07 +08:00

55 lines
1.8 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* File: permutations_i.cpp
* Created Time: 2023-04-24
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* Алгоритм бэктрекинга: все перестановки I */
void backtrack(vector<int> &state, const vector<int> &choices, vector<bool> &selected, vector<vector<int>> &res) {
// Когда длина состояния равна числу элементов, записать решение
if (state.size() == choices.size()) {
res.push_back(state);
return;
}
// Перебор всех вариантов выбора
for (int i = 0; i < choices.size(); i++) {
int choice = choices[i];
// Отсечение: нельзя выбирать один и тот же элемент повторно
if (!selected[i]) {
// Попытка: сделать выбор и обновить состояние
selected[i] = true;
state.push_back(choice);
// Перейти к следующему выбору
backtrack(state, choices, selected, res);
// Откат: отменить выбор и восстановить предыдущее состояние
selected[i] = false;
state.pop_back();
}
}
}
/* Все перестановки 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 << "Входной массив nums = ";
printVector(nums);
cout << "Все перестановки res = ";
printVectorMatrix(res);
return 0;
}