From 60bbfc42e53f0087a0a72d413d78ead9b2b49f61 Mon Sep 17 00:00:00 2001 From: Pegasus02K Date: Sun, 17 Apr 2022 23:19:27 +0900 Subject: [PATCH 1/2] Create 131-Palindrome-Partitioning.cpp C++ solution for 131-Palindrome-Partitioning --- cpp/131-Palindrome-Partitioning.cpp | 36 +++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 cpp/131-Palindrome-Partitioning.cpp diff --git a/cpp/131-Palindrome-Partitioning.cpp b/cpp/131-Palindrome-Partitioning.cpp new file mode 100644 index 000000000..175238d97 --- /dev/null +++ b/cpp/131-Palindrome-Partitioning.cpp @@ -0,0 +1,36 @@ +class Solution { +public: + bool isPali(const string& s, int l, int r) { + while (l < r) { + if (s[l] != s[r]) + return false; + ++l, --r; + } + return true; + } + + void solve(const string& s, vector>& res, vector& part, int i) { + if (i >= s.size()) { + res.push_back(part); + return; + } + for (int j = i; j < s.size(); ++j) { + if (isPali(s, i, j)) { + // i~j substr is palindrome + part.push_back(s.substr(i, j - i + 1)); + // check next substring + solve(s, res, part, j); + // backtrack + part.pop_back(); + } + } + } + + vector> partition(string s) { + vector> res; + vector part; + + solve(s, res, part, 0); + return res; + } +}; From dd6ba062baacf8d107599eccbe56f4ecf22cacf4 Mon Sep 17 00:00:00 2001 From: Pegasus02K Date: Sun, 17 Apr 2022 23:22:58 +0900 Subject: [PATCH 2/2] Update 131-Palindrome-Partitioning.cpp --- cpp/131-Palindrome-Partitioning.cpp | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/cpp/131-Palindrome-Partitioning.cpp b/cpp/131-Palindrome-Partitioning.cpp index 175238d97..5eb907ab0 100644 --- a/cpp/131-Palindrome-Partitioning.cpp +++ b/cpp/131-Palindrome-Partitioning.cpp @@ -9,18 +9,15 @@ class Solution { return true; } - void solve(const string& s, vector>& res, vector& part, int i) { - if (i >= s.size()) { + void solve(const string& s, vector>& res, vector& part, int idx) { + if (idx >= s.size()) { res.push_back(part); return; } - for (int j = i; j < s.size(); ++j) { - if (isPali(s, i, j)) { - // i~j substr is palindrome - part.push_back(s.substr(i, j - i + 1)); - // check next substring - solve(s, res, part, j); - // backtrack + for (int j = idx; j < s.size(); ++j) { + if (isPali(s, idx, j)) { + part.push_back(s.substr(idx, j - idx + 1)); + solve(s, res, part, j + 1); part.pop_back(); } }