Palindrome Partitioning(DFS)

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"]
  ]
 1 class Solution {
 2     public:
 3         vector<vector<string> > ans_m;
 4         vector<string> ans_v;
 5         
 6         bool IsPalindrome(const string & s){
 7             int i = 0; 
 8             int j = s.size() -1;
 9             //这里之前有一个bug,while(i != j) 比如 bb的情况,一下子 i = 1, j = 0, 然后就会越界访问 core dump
10             while(i < j){
11                 if (s.at(i) == s.at(j)){
12                     i++;
13                     j--;
14                 }else{
15                     return false;
16                 }
17             }
18             return true;
19         }
20         //这里dfs的意思是说从start的位置出发,找最近的回文串,然后继续递归
21         // abbab-> 'a' 'b' 'b' 'a' 'b' path  OK
22         // abbab-> 'a' 'b'             退栈直到 path
23         // abbab-> 'a' 'b'  'bab'      path  OK
24         // abbab-> 'a' 'bb' 'a' 'b'    path  OK
25         // abbab-> ''                  path --> 一直退栈
26         // abbab-> 'abba' 'b'          path  OK
27         
28         //如果是显式的给出图
29         /*                  root
30                          /         \
31                            a           abba
32                       /  \            \
33                      b   'bb'          'b'
34                     /  \    \           \
35                    b   'bab' 'a'         OK
36                   /       \    \
37                  a         OK   'b'
38                 /                 \
39                b                   OK
40               /
41              OK
42             
43             一目了然,你可以理解为图的DFS,也可以理解为树的DFS,Path就是记录路径的。
44             因为本质是一棵树,不会重复访问,也不需要VISIT数组
45             for循环本质是判断当前节点下有多少领接的边
46             
47             以后对于这种题目,先写出表达式tree或者graph,然后再去遍历
48         */
49         void dfs(string s, int start, vector<string> & path){
50             if (start == s.size()){
51                 ans_m.push_back(path); //搜索退出的条件 搜到整个字符串完成为止
52                 return;
53             }
54             for(int i = start + 1; i <= s.size(); i++){ //确定当前start位置出发的回文串
55                 string sub_s = s.substr(start,i - start);
57                 if (IsPalindrome(sub_s)){
59                     path.push_back(sub_s);
60                     dfs(s,i,path);
61                     path.resize(path.size() -1);
62                 }
63             }
64         }
65         vector<vector<string> > partition(string s) {
66             ans_m.clear();
67             ans_v.clear();
68             dfs(s,0,ans_v);
69             return ans_m;                 
70         }
71 };v

 

posted @ 2013-06-11 20:03  一只会思考的猪  阅读(227)  评论(0编辑  收藏  举报