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"]
]
The first to see this problem without thinking, may be to see a palindrome afraid. I can't figure out how to use backtracking to solve it.
So on the paper casually scribble some, the result found that seems to be able to follow the idea of solving, it is very embarrassing ah.
For the above "AAB" as input, you can look for a palindrome:
"A" + "AB" composed of palindrome string
"AA" + "B" constitute a palindrome string
"AaB" is not a palindrome, so exit directly.
So the feeling for a string, you can traverse the string, if the former POS string itself is a back-word character, then only need to solve the following sub-character palindrome string, so this problem is broken down into a smaller problem. This problem is more like a divide-and-conquer question, shrinking the size of the issue, and of course, the process of traversing a string requires backtracking.
In addition to the need for a recursive helper function, it is also necessary to define a helper function that determines whether a string is a textual character string, and the logic of the program is very simple.
This question and combination Sum is similar, at the beginning to see this problem completely feel impossible, but write a few test cases on paper, from the special test cases can be found in the law. And after the retrospective recursion is not so clear, there may be a test is easier to understand some of the meeting.
Runtime:20ms
classSolution { Public: vector<vector<string>>Partitionstrings) { vector<string>Path vector<vector<string>>Result Helper (S,0, Path,result);returnResult }voidHelperstringSintPos vector<string>& Path, vector<vector<string>>& result) {if(Pos==s.size ()) {result.push_back (path);return; } for(intI=pos;i<s.size (); i++) {if(Ispalindrome (S.substr (pos,i-pos+1)) {Path.push_back (S.substr (pos,i-pos+1)); Helper (s,i+1, Path,result); Path.pop_back (); } } }BOOLIspalindrome (strings) {intfirst=0;intEnd=s.size ()-1; while(First<end) {if(s[first++]!=s[end--])return false; }return true; }};
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode131:palindrome Partitioning