From cea6c387a3c29fa68dfbd37fff1aba082354442b Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Fri, 3 Feb 2023 16:42:37 +0800 Subject: [PATCH] s0046 --- include/s0046_permutations.hpp | 13 +++++++++++++ notes/src/SUMMARY.md | 1 + notes/src/permute.md | 3 +++ src/s0046_permutations.cpp | 31 +++++++++++++++++++++++++++++++ 4 files changed, 48 insertions(+) create mode 100644 include/s0046_permutations.hpp create mode 100644 notes/src/permute.md create mode 100644 src/s0046_permutations.cpp diff --git a/include/s0046_permutations.hpp b/include/s0046_permutations.hpp new file mode 100644 index 0000000..40122aa --- /dev/null +++ b/include/s0046_permutations.hpp @@ -0,0 +1,13 @@ +#ifndef S0046_PERMUTATIONS_HPP +#define S0046_PERMUTATIONS_HPP + +#include + +using namespace std; + +class S0046 { + public: + vector> permute(vector& nums); +}; + +#endif diff --git a/notes/src/SUMMARY.md b/notes/src/SUMMARY.md index 600c238..3fb8699 100644 --- a/notes/src/SUMMARY.md +++ b/notes/src/SUMMARY.md @@ -44,6 +44,7 @@ - [组合问题](./combinations.md) - [切割问题](./split.md) - [子集问题](./subsets.md) +- [排列问题](./permute.md) # STL diff --git a/notes/src/permute.md b/notes/src/permute.md new file mode 100644 index 0000000..7ac49ba --- /dev/null +++ b/notes/src/permute.md @@ -0,0 +1,3 @@ +# 排列问题 + +## [46. 全排列](https://leetcode.cn/problems/permutations/) diff --git a/src/s0046_permutations.cpp b/src/s0046_permutations.cpp new file mode 100644 index 0000000..24163fd --- /dev/null +++ b/src/s0046_permutations.cpp @@ -0,0 +1,31 @@ +#include "s0046_permutations.hpp" + +void permuteDFS(vector &path, vector> &result, + vector &used, vector &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> S0046::permute(vector &nums) { + vector path{}; + vector> result{}; + vector used(nums.size(), false); + permuteDFS(path, result, used, nums); + return result; +}