LeetCode131: Palindrome Partitioning
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab ",
Return
[
["Aa", "B"],
["A", "a", "B"]
]
When I first saw this question, I had no idea. Maybe I was afraid of reading the text back. I cannot figure out how to use backtracking to solve the problem.
As a result, I randomly drew some pictures on the paper and found that I could solve the problem by following this idea.
For the above "aab" as the input, you can search for the reply as follows:
Input string composed of "a" + "AB"
Input string consisting of "aa" + "B"
"Aab" does not return text, so it exits directly.
As a result, we feel that a string can be traversed. If the first pos string is a return character, we only need to solve the return string of the subcharacters, this problem is broken down into a smaller one. This question is more like a divide-and-conquer question, which will narrow down the problem scale. Of course, the process of traversing strings needs to be traced back.
In addition to a recursive auxiliary function, you also need to define an auxiliary function to judge whether a string is a return string. The program logic is very simple.
This question is similar to Combination Sum. When we first saw this question, we had no idea how to do it. However, we wrote several test cases on paper to find the rule from special test cases. In addition, the recursion after Backtracking is not so clear at a glance, and it may be easier for some testing cases to understand.
Runtime: 20 ms
class Solution {public: vector
> partition(string s) { vector
path; vector
> result; helper(s,0,path,result); return result; } void helper(string s,int pos,vector
& path,vector
> & result) { if(pos==s.size()) { result.push_back(path); return ; } for(int i=pos;i