This commit is contained in:
parent
3171c30f82
commit
cea6c387a3
13
include/s0046_permutations.hpp
Normal file
13
include/s0046_permutations.hpp
Normal file
@ -0,0 +1,13 @@
|
||||
#ifndef S0046_PERMUTATIONS_HPP
|
||||
#define S0046_PERMUTATIONS_HPP
|
||||
|
||||
#include <vector>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class S0046 {
|
||||
public:
|
||||
vector<vector<int>> permute(vector<int>& nums);
|
||||
};
|
||||
|
||||
#endif
|
@ -44,6 +44,7 @@
|
||||
- [组合问题](./combinations.md)
|
||||
- [切割问题](./split.md)
|
||||
- [子集问题](./subsets.md)
|
||||
- [排列问题](./permute.md)
|
||||
|
||||
# STL
|
||||
|
||||
|
3
notes/src/permute.md
Normal file
3
notes/src/permute.md
Normal file
@ -0,0 +1,3 @@
|
||||
# 排列问题
|
||||
|
||||
## [46. 全排列](https://leetcode.cn/problems/permutations/)
|
31
src/s0046_permutations.cpp
Normal file
31
src/s0046_permutations.cpp
Normal file
@ -0,0 +1,31 @@
|
||||
#include "s0046_permutations.hpp"
|
||||
|
||||
void permuteDFS(vector<int> &path, vector<vector<int>> &result,
|
||||
vector<bool> &used, vector<int> &nums) {
|
||||
int len = nums.size();
|
||||
// 终止条件
|
||||
if (path.size() == len) {
|
||||
result.push_back(path);
|
||||
return;
|
||||
}
|
||||
|
||||
// 开始迭代
|
||||
for (int i{0}; i < len; ++i) {
|
||||
// 如果当前元素使用过,则跳过
|
||||
if (used[i]) continue;
|
||||
// 否则处理当前节点
|
||||
path.push_back(nums[i]);
|
||||
used[i] = true;
|
||||
permuteDFS(path, result, used, nums);
|
||||
used[i] = false;
|
||||
path.pop_back();
|
||||
}
|
||||
}
|
||||
|
||||
vector<vector<int>> S0046::permute(vector<int> &nums) {
|
||||
vector<int> path{};
|
||||
vector<vector<int>> result{};
|
||||
vector<bool> used(nums.size(), false);
|
||||
permuteDFS(path, result, used, nums);
|
||||
return result;
|
||||
}
|
Loading…
Reference in New Issue
Block a user