From fc3c9ad297c45c1705967fd5fd95f713fb76d6f7 Mon Sep 17 00:00:00 2001 From: Zhao Zihe Date: Tue, 9 Oct 2018 21:55:48 +0800 Subject: [PATCH] Permutations CPP MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 排列数,模板题 --- solution/046.Permutations/Solution.cpp | 35 ++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 solution/046.Permutations/Solution.cpp diff --git a/solution/046.Permutations/Solution.cpp b/solution/046.Permutations/Solution.cpp new file mode 100644 index 0000000000000..53c6d493ec0e7 --- /dev/null +++ b/solution/046.Permutations/Solution.cpp @@ -0,0 +1,35 @@ +class Solution { +public: + vector> permute(vector& nums) { + if (nums.size() == 0) return{}; + vector> res; + vector curr_vec; + vector used; + for (int i = 0; i < nums.size(); i++) + { + used.push_back(false); + } + dfs(res, nums, 0, curr_vec, used); + return res; + } + + void dfs(vector>& res, vector& nums, int depth, vector curr_vec, vector used) + { + + if (depth >= nums.size()) + { + res.emplace_back(curr_vec); + return; + } + + for (int i = 0; i < nums.size(); i++) + { + if (used[i]) continue; + used[i] = true; + curr_vec.emplace_back(nums[i]); + dfs(res, nums, depth + 1, curr_vec, used); + curr_vec.pop_back(); + used[i] = false; + } + } +};