Palindrome Partitioning--LeetCode

桃扇骨 2022-08-07 12:56 26阅读 0赞

题目:

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

  1. [
  2. ["aa","b"],
  3. ["a","a","b"]
  4. ]

思路:我们从第一个字符开始直到最后一个字符,一旦有可以构造成回文的字符串,继续判断剩下的字符串是否可以构造成回文字符串。直到真个字符串都构造结束,输出构成的方式。使用一个向量记录构成的方式。

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. using namespace std;
  5. bool check(string& str,int begin,int end)
  6. {
  7. int i = begin ;
  8. int j = end;
  9. for(;i<=j;i++,j--)
  10. if(str[i] != str[j])
  11. return false;
  12. return true;
  13. }
  14. void helper(string& str,int begin,int end,vector<int>& pos)
  15. {
  16. int i,j,k;
  17. if(begin > end)
  18. {
  19. for(j=0;j<pos.size();j++)
  20. {
  21. cout<<str[j];
  22. if(pos[j] != -1)
  23. {
  24. cout<<",";
  25. pos[j] = -1;
  26. }
  27. }
  28. cout<<endl;
  29. }
  30. for(i= begin;i<=end;i++)
  31. {
  32. if(check(str,begin,i))
  33. {
  34. pos[i] = i-begin+1;
  35. helper(str,i+1,end,pos);
  36. }
  37. }
  38. }
  39. void PalindromePartition(string& str)
  40. {
  41. if(str.length() == 0)
  42. return ;
  43. vector<int> pos(str.length(),-1);
  44. helper(str,0,str.length()-1,pos);
  45. }
  46. int main()
  47. {
  48. string str("aab");
  49. PalindromePartition(str);
  50. system("pause");
  51. return 0;
  52. }

这也是一个典型的回溯问题,但是有的同学可能认为什么没有发现pos发生回溯的现象,也就是恢复原状的现象呢,因为在传递pos数组时传递的是已经分配好空间的数组,这个关于回溯使用这种方案,可以参考数据结构与算法系列中矩阵走的路径那个问题。

发表评论

表情:
评论列表 (有 0 条评论,26人围观)

还没有评论,来说两句吧...

相关阅读