• 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"]
      ]
    

    Restore IP Addresses类似。。都使用回溯法。。。

    C++实现代码:

    #include<iostream>
    #include<vector>
    #include<string>
    using namespace std;
    
    class Solution
    {
    public:
        vector<vector<string>> partition(string s)
        {
            if(s.empty())
                return vector<vector<string> >();
            vector<vector<string> > ret;
            vector<string> path;
            helper(s,0,ret,path);
            return ret;
        }
        void helper(string s,int start,vector<vector<string> > &ret,vector<string> &path)
        {
            int n=path.size();
            int i;
            int sum=0;
            for(int j=0; j<n; j++)
            {
                sum+=path[j].size();
            }
    
            if(sum==(int)s.size())
            {
                ret.push_back(path);
                return;
            }
         //start+i<=(int)s.size()是为了分割的最后一个字符串不重复。
    for(i=1; i<=(int)s.size()&&start+i<=(int)s.size(); i++) { string tmp=s.substr(start,i); if(!isPalindrome(tmp)) continue; path.push_back(tmp); helper(s,start+i,ret,path); path.pop_back(); } } bool isPalindrome(string s) { if(s.empty()) return true; int i=0; int j=s.length()-1; while(i<=j) { if(s[i]!=s[j]) return false; i++; j--; } if(i>j) return true; return false; } }; int main() { Solution s; vector<vector<string> > result=s.partition(string("aab")); for(auto a:result) { for(auto v:a) cout<<v<<" "; cout<<endl; } }

    运行结果:

     
  • 相关阅读:
    初识增长黑客Growth Hacker
    OpenCV学习目录(持续更新)
    leetcode算法-回文判断
    leetcode算法-整数反转
    日常撸题技巧【总结】
    hihocoder 题目类型整理
    【hiho】92-93--素数【数论】
    notepad打造成C/C++IDE【Notepad】
    ACM知识点总结【杂】
    Nastya Studies Informatics
  • 原文地址:https://www.cnblogs.com/wuchanming/p/4128974.html
Copyright © 2020-2023  润新知