【Leetcode】【Medium】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"]
  ]

 

解题:

使用深入优先搜索的思想;使用递归;

从头i = 0开始遍历字符串,找到满足要求的回文列,将其放入结果列表中,继续查找下面的回文字符;

 

解题步骤:

1、主函数,建立返回的二维数组,建立存放结果的一维数组,调用递归函数;

2、递归函数,输入为二维数组ret,一维数组path,字符串str,当前检查到的index值:

  (1)如果index值已经等于str的长度,说明搜索完毕,将path插入ret中,返回;

  (2)否则从i从index开始,遍历到str末尾,找index~i范围哪些是回文串:

    a. 将回文串摘出放入path中,更新index,继续递归;

    b. 从path中pop出放入的回文串,继续遍历循环;

3、返回ret

 

代码:

 1 class Solution {
 2 public:
 3     vector<vector<string>> partition(string s) {
 4         vector<vector<string> > ret;
 5         if(s.empty()) 
 6             return ret;
 7 
 8         vector<string> path;
 9         dfs(ret, path, s, 0);
10 
11         return ret;
12     }
13 
14     void dfs(vector<vector<string> >& ret, vector<string>& path, string& s, int index) {
15         if(index == s.size()) {
16             ret.push_back(path);
17             return;
18         }
19         
20         for(int i = index; i < s.size(); ++i) {
21             // find all palindromes begin with index
22             if(isPalindrome(s, index, i)) {
23                 path.push_back(s.substr(index, i - index + 1));
24                 dfs(ret, path, s, i+1);
25                 path.pop_back();
26             }
27         }
28     }
29 
30     bool isPalindrome(const string& s, int start, int end) {
31         while(start <= end) {
32             if(s[start++] != s[end--])
33                 return false;
34         }
35         return true;
36     }
37 };

 

 


posted @ 2015-09-01 22:41  胡潇  阅读(760)  评论(0编辑  收藏  举报