zoukankan      html  css  js  c++  java
  • LeetCode131: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”]
    ]

    最開始看到这道题时毫无思路。可能是看到回文就怕了。也想不出怎样用回溯来求解。

    于是在纸上随便乱画了一些,结果发现好像能够依照这个思路求解了,简直囧啊。

    对于上面的”aab”作为输入。能够这么寻找回文:
    “a”+”ab”构成的回文串
    “aa”+”b”构成的回文串
    “aab”不是回文。所以直接退出。

    于是感觉对于一个字符串,能够对这个字符串进行遍历,假设前pos个字符串本身是个回文字符。那么仅仅须要求解后面的子字符的回文串就可以,于是这个问题被分解成了一个更小的问题。

    这道题更像一个分治法的题,将问题规模不断缩小,当然的遍历字符串的过程中须要进行回溯。

    除了须要一个进行递归的辅助函数外。还须要定义一个推断一个字符串是否是回文字符串的辅助函数。程序的逻辑很easy。

    这道题和Combination Sum 比較相似,一開始看到这道题时全然感觉无从下手,可是在纸上写几个測试用例,从特殊的測试用例中就能够发现规律了。加上回溯后的递归都没有那么一目了然,可能有測试用例会更easy懂一些。


    runtime:20ms

    class Solution {
    public:
        vector<vector<string>> partition(string s) {
            vector<string> path;
            vector<vector<string>> result;
            helper(s,0,path,result);
            return result;
        }
    
        void helper(string s,int pos,vector<string> & path,vector<vector<string>> & result)
        {
            if(pos==s.size())
            {
                result.push_back(path);
                return ;
            }
            for(int i=pos;i<s.size();i++)
            {
                if(isPalindrome(s.substr(pos,i-pos+1)))
                {
                    path.push_back(s.substr(pos,i-pos+1));
                    helper(s,i+1,path,result);
                    path.pop_back();
                }
            }
        }
    
        bool isPalindrome(string s)
        {
            int first=0;
            int end=s.size()-1;
            while(first<end)
            {
                if(s[first++]!=s[end--])
                    return false;
            }
            return true;
        }
    };
  • 相关阅读:
    hdu1087Super Jumping! Jumping! Jumping!
    hdu1159Common Subsequence(最长公共子序列)
    hdu1069Monkey and Banana(最长递增子序列)
    poj2533(最长递增子序列)
    hdu1029Ignatius and the Princess IV
    uva10622(唯一分解定理)
    myeclipse设置技巧
    myeclipse2014新感悟
    小错误汇总
    字符串反转
  • 原文地址:https://www.cnblogs.com/gccbuaa/p/7392227.html
Copyright © 2011-2022 走看看