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

    填写dp矩阵的时候坐标弄反了浪费了好多时间……
    class Solution {
    public:
        vector<vector <int> >dp;
        vector<vector<string>> re;
        int len;
        vector<vector<string>> partition(string s) {
            
            string ss ="";
            if(s.size() == 0)return re;
            if(s.size()==1)
            {
                vector<string> tp ;
                tp.push_back(s);
                re.push_back(tp);
                return re;
            }
            ss = ss+s[0];
            for(int i = 1 ; i  < s.length();i++)
            {
                ss = ss + "#";
                ss = ss + s[i];
            }
            len = ss.size();
            
            
            for(int i = 0 ; i < len ;i++)
            {
                vector<int> tp(len,0);
                dp.push_back(tp);
            }
            for(int i  = 0  ; i < len ; i++)
            dp[i][i] = 1;
            
            for(int i = 0  ; i < len ;i++)
            {
                int j = 1;
                while(i-j>=0 && i+j<len && ss[i-j] == ss[i+j])
                {
                    dp[i-j][i+j] = 1;
                    j++;
                }
            }
            vector<string> temp;
            fill(0,temp,s);
            return re;
        }
        void fill(int n, vector<string> now,string s)
        {
            if(n >= len)
            {
                re.push_back(now);
                return;
            }
            for(int i = n ; i < len ;i++)
            {
                if(dp[n][i] == 1)
                {
                    if(n%2 == 0)
                        {
                            string sub =s.substr(n/2,i/2-n/2+1);
                            if(sub == "")continue;
                            now.push_back(sub);
                        }
                        else
                        {
                            string sub =s.substr((n+1)/2,(i+1)/2-(n+1)/2);
                            if(sub == "")continue;
                            now.push_back(sub);
                        }
                        fill(i+2,now,s);
                        now.pop_back();
                }
            }
        }
    };
    

      

  • 相关阅读:
    Dice 5 ==> dice 7
    Dice 7 ==> dice 5
    100 floors 2 eggs
    Determine overlapping rectangles
    Product of integers
    Maximum profit of stocks
    样式表
    20170508
    2017年05月07
    The second day of school
  • 原文地址:https://www.cnblogs.com/pengyu2003/p/3666630.html
Copyright © 2011-2022 走看看