diff --git a/cpp/131-Palindrome-Partitioning.cpp b/cpp/131-Palindrome-Partitioning.cpp new file mode 100644 index 000000000..5eb907ab0 --- /dev/null +++ b/cpp/131-Palindrome-Partitioning.cpp @@ -0,0 +1,33 @@ +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 idx) { + if (idx >= s.size()) { + res.push_back(part); + return; + } + 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(); + } + } + } + + vector> partition(string s) { + vector> res; + vector part; + + solve(s, res, part, 0); + return res; + } +};