Topic:
Given A string s, partition s such that every substring of the partition are a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab" ,
Return
[ ["AA", "B"], ["A", "a", "B"] ]
idea: We need to split a string into the form of a palindrome substring, and then return all the split results. Need two auxiliary functions, one is recursive DFS, help us to split the string, we can learn from the addresses of the Restore IP, we loop all the split length, starting from 1 until the length of the remaining substring (note that you can take the equal sign i = s.size ()), Then determine whether this substring is a palindrome, you can draw on the method in valid palindrome, we set two coordinates from the beginning to judge, while moving, if there is not equal return false. If the substring is a palindrome and is added to the TMP result, the remaining string is passed to the helper function to continue recursion until the remaining substring is empty, returning the result. The important thing is that we need to maintain the site and pop_back the results of the added substring. This guarantees that the next time you select a different length, there are no repeating characters in the result.
Attention:
1. Iteration termination condition, the remaining substring length is 0.
if (s.size () = = 0) { ret.push_back (TMP); return; }
2. Recursively select the remaining substrings at a time. After the recursion is over, the site should be maintained.
int strlen = S.size (); Tmp.push_back (substr); Partition_helper (S.substr (i, strlen-i), TMP, ret); Tmp.pop_back ();
3. I represents the length of the split substring, not the coordinates, so the length can take the length of the string. Note take the equal sign.
for (int i = 1; I <= s.size (); i++)
Complexity: Depending on the number of results, the worst case is the order of magnitude.
AC Code:
Class solution {public:vector<vector<string>> partition (string s) {vector<vector<string>& Gt Ret if (s.size () = = 0) return ret; vector<string> tmp; Partition_helper (S, TMP, RET); return ret; }private:void Partition_helper (string s, vector<string> tmp, vector<vector<string>>& ret) { if (s.size () = = 0) {ret.push_back (TMP); Return } for (int i = 1; I <= s.size (); i++) {String substr = s.substr (0, I); if (Ispalindrome (substr)) {int strlen = S.size (); Tmp.push_back (SUBSTR); Partition_helper (S.substr (i, strlen-i), TMP, ret); Tmp.pop_back (); }}}//Assuming no other characters including spaces, including lowercase letter bool Ispalindrome (string s) {int len = s.size (); if (len = = 0 | | len = = 1) return true; int i = 0; Int J = len-1; while (I < j) {if (s[i++]! = s[j--]) {return false; }} return true; }};
[C + +] leetcode:121 palindrome Partitioning (split palindrome substring backtracking method)