码迷,mamicode.com
首页 > 其他好文 > 详细

【Palindrome Partitioning】cpp

时间:2015-05-26 18:03:37      阅读:129      评论:0      收藏: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

  [
    ["aa","b"],
    ["a","a","b"]
  ]

代码:

class Solution {
public:
    vector<vector<string>> partition(string s) {
            vector<vector<string> > ret;
            vector<string> tmp;
            Solution::dfs(ret, tmp, s, 0, s.size()-1);
            return ret;
    }
    static void dfs(vector<vector<string> >& ret, vector<string>& tmp, string& s, int begin, int end)
    {
            if ( begin>end ) { ret.push_back(tmp); return; }
            for ( int i = begin; i <= end; ++i )
            {
                if ( Solution::isPalindrome(s, begin, i) )
                {
                    tmp.push_back(s.substr(begin,i-begin+1));
                    Solution::dfs(ret, tmp, s, i+1, end);
                    tmp.pop_back();
                }
            }
    }
    static bool isPalindrome(string& s, int begin, int end)
    {
            while ( begin<end && s[begin]==s[end] ) { begin++; end--; }
            return begin>=end;
    }
};

tips:

把问题转化为深搜:字符串s有n个字符,因此可以有n个切的位置(包括不切)。

按照深搜的模板写出来代码(dfs终止条件;深搜遍历条件等)。

注意一个细节,传入下一层dfs时是从i+1到end,之前一直写成了begin+1犯了低级错误。

深搜的时间复杂度为O(2^n) 空间复杂度为O(1)。

深搜在这道题上也有不足之处,很多子字符串是否是回文算过了不止一遍,自然联想能否用动规算法保存每一轮的判断结果。

====================================================

先往后走,后面再研究动态规划的做法。

【Palindrome Partitioning】cpp

标签:

原文地址:http://www.cnblogs.com/xbf9xbf/p/4530751.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!