131.Palindrome Partitioning === ###### tags: `Medium`,`String`,`Backtracking`,`DP` [131. Palindrome Partitioning](https://leetcode.com/problems/palindrome-partitioning/description/) ### 題目描述 Given a string `s`, partition s such that every substring of the partition is a palindrome. Return *all possible palindrome partitioning of* `s`. ### 範例 **Example 1:** ``` Input: s = "aab" Output: [["a","a","b"],["aa","b"]] ``` **Example 2:** ``` Input: s = "a" Output: [["a"]] ``` **Constraints**: * 1 <= s.length <= 16 * `s` contains only lowercase English letters. ### 解答 #### C++ ```cpp= class Solution { public: vector<vector<string>> ans; bool isPalindrome(const string& s) { int start = 0, end = s.size() - 1; while (start <= end) { if (s[start++] != s[end--]) return false; } return true; } void BT(const string& s, vector<string>& path, int cur = 0) { if (cur == s.size()) { ans.push_back(path); return; } for (int i = cur; i < s.size(); i++) { string substring = s.substr(cur, i - cur + 1); if (isPalindrome(substring)) { path.push_back(substring); BT(s, path, i + 1); path.pop_back(); } } } vector<vector<string>> partition(string s) { vector<string> path; BT(s, path); return ans; } }; ``` > [name=Yen-Chi Chen][time=Sun, Jan 22, 2023] #### Python ```python= class Solution: def partition(self, s: str) -> List[List[str]]: ans = [] def isPalindrome(s): return s == s[::-1] def BT(path = [], index = 0): if index == len(s): ans.append(path) return for i in range(index, len(s)): sub = s[index:i+1] if isPalindrome(sub): BT(path + [sub], i + 1) BT() return ans ``` > [name=Yen-Chi Chen][time=Sun, Jan 22, 2023] ### Reference [回到題目列表](https://hackmd.io/@Marsgoat/leetcode_every_day)