leetcode Palindrome Partitioning

I
一次accept,dfs
class Solution {
public:
vector<vector<string>>v;
vector<string>v1;
    vector<vector<string>> partition(string s) 
    {
       v.clear();
       if(s.size()==0)return v;
       v1.clear();
       dfs(0,s);
       return v;          
    }
    bool ishui(string s)
    {
        int i=0,j=s.size()-1;
        while(i<j)
        {
            if(s[i]==s[j])
            {
                i++;j--;
            }
            else return false;
        }
        return true;
    }    
     void dfs(int depth,string s)
     {
        if(depth==s.size())
        {
            v.push_back(v1);
        }
        if(depth<s.size())
        {
            for(int i=depth;i<s.size();i++)
            {
                if(ishui(s.substr(depth,i-depth+1)))
                {
                    v1.push_back(s.substr(depth,i-depth+1));
                    dfs(i+1,s); 
                    v1.pop_back();                    
                }
            }
        }
    }
};

 II

DFS直接导致judge large超时,采用dp,参考官网非常牛逼的解法!

class Solution {
public:
    int minCut(string str){

        int leng = str.size();

        int dp[leng+1];
        bool palin[leng][leng];

      for(int i = 0; i <= leng; i++)
        dp[i] = leng-i;
        for(int i = 0; i < leng; i++)
            for(int j = 0; j < leng; j++)
                palin[i][j] = false;

      for(int i = leng-1; i >= 0; i--){
        for(int j = i; j < leng; j++){
          if(str[i] == str[j] && (j-i<2 || palin[i+1][j-1])){
            palin[i][j] = true;
            dp[i] = min(dp[i],dp[j+1]+1);
          }
        }
      }
      return dp[0]-1;
    }
};
原文地址:https://www.cnblogs.com/tgkx1054/p/3114178.html