From b957332a5ec6c6ceb6247be047ca8316cffc22fa Mon Sep 17 00:00:00 2001 From: Zhao Zihe Date: Wed, 10 Oct 2018 21:34:02 +0800 Subject: [PATCH] Add C++ solution to 047 Add C++ solution to 047 --- solution/047.Permutations II/Solution.cpp | 41 +++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 solution/047.Permutations II/Solution.cpp diff --git a/solution/047.Permutations II/Solution.cpp b/solution/047.Permutations II/Solution.cpp new file mode 100644 index 0000000000000..ebbe22110bc39 --- /dev/null +++ b/solution/047.Permutations II/Solution.cpp @@ -0,0 +1,41 @@ +class Solution { +public: + vector> permuteUnique(vector& nums) { + if (nums.size() <= 0) return{}; + + sort(nums.begin(), nums.end()); + + vector> res; + vector used; + vector curr; + + for (auto item : nums) + { + used.push_back(false); + } + + dfs(res, nums, curr, used, 0); + return res; + } + + void dfs(vector>& res, vector& nums, vector curr, vector used, int depth) + { + if (depth >= nums.size()) + { + res.emplace_back(curr); + return; + } + + for (int i = 0; i < nums.size(); i++) + { + if (used[i]) continue; + if (i > 0 && nums[i] == nums[i - 1] && !used[i-1]) continue; + + used[i] = true; + curr.emplace_back(nums[i]); + dfs(res, nums, curr, used, depth + 1); + curr.pop_back(); + used[i] = false; + } + } +};