https://leetcode.com/problems/palindrome-partitioning/

1. Use backtracking:

  1. //60 ms 15.8 MB
  2. class Solution {
  3. public:
  4. vector<vector<string>> partition(string s) {
  5. vector<string> path;
  6. vector<vector<string>> result;
  7. backtrack(s, path, result, 0);
  8. return result;
  9. }
  10. private:
  11. bool isPallindrome(string s){
  12. int l = 0, r = s.length()-1;
  13. while(l < r){
  14. if(s[l] != s[r]){
  15. return false;
  16. }
  17. l++;
  18. r--;
  19. }
  20. return true;
  21. }
  22. void backtrack(string s, vector<string>& path, vector<vector<string>>& result, int pos){
  23. int n = s.size();
  24. if(pos == n){
  25. result.push_back(path);
  26. return;
  27. }
  28. for(int i=1; i<= n - pos; i++){
  29. if(isPallindrome(s.substr(pos, i))){
  30. path.push_back(s.substr(pos, i));
  31. backtrack(s, path, result, pos+i);
  32. path.pop_back();
  33. }
  34. }
  35. }
  36. };