Description
Given a stringS, SetSIt is split into several substrings so that each substring is a return string.
ReturnSAll possible splitting schemes.
Example:
Input: "AAB" output: [["AA", "B"], ["A", "A", "B"]
Solutions
Backtracking. First, traverse the substrings of a string, record whether the strings are input strings, and then recursively judge the input strings and add them to the result set.
Code
1 class Solution { 2 public: 3 vector<vector<string>> partition(string s) { 4 vector<vector<string>> res; 5 vector<vector<int>> strHuiwen(s.length(), vector<int>(s.length(), 0)); 6 vector<string> temp; 7 for(int i = 0; i < s.length(); i++) 8 for(int j = i; j < s.length(); j++) 9 if(isHuiwen(s.substr(i, j - i + 1)))10 strHuiwen[i][j] = 1;11 huiwen(s, 0, res, temp, strHuiwen);12 return res;13 }14 void huiwen(string s, int idx, vector<vector<string>> &res, vector<string> &temp, vector<vector<int>> strHuiwen){15 if(idx == s.length()){16 res.push_back(temp);17 return;18 }19 for(int i = idx; i < s.length(); i++){20 if(strHuiwen[idx][i]){21 temp.push_back(s.substr(idx, i - idx + 1));22 huiwen(s, i + 1, res, temp, strHuiwen);23 temp.pop_back();24 }25 }26 }27 bool isHuiwen(string s){28 for(int i = 0; i < s.length() / 2; i++)29 if(s[i] != s[s.length() - i - 1]) return false;30 return true;31 }32 };
Leetcode 131. Split the palindrome partitioning)