131.leetcode-Palindrome Partitioning

解法一.

   

class Solution {
public:
    vectorstring>> partition(string s) {
        vectorstring> > res;
        vector<string> cur;
        DFS(res, cur, s, 0);
        return res;
    }
    
    void DFS(vectorstring> >& res, vector<string>& cur, string s, int start)
    {
        if(start >= s.size())
        {
            res.push_back(cur);
            return ;
        }    
        for(int i = start; i < s.size(); i++)
        {
            if(ispalindrome(s, start, i)) 
            {
                cur.push_back(s.substr(start, i-start+1));
                DFS(res, cur, s, i+1);
                cur.pop_back();
            }
        }
    }
    
    bool ispalindrome(string s, int start, int end)
    {
        while(start < end)
        {
            if(s[start++] != s[end--])
                return false;
        }
        return true;
    }
};

 

对于解法一,每次要求是否为回文串导致时间效率降低

解法二使用DP先求出回文串,然后直接DFS效率会高一点,可是空间效率会降低

class Solution {
public:
    vectorstring>> partition(string s) {
        vectorstring> > res;
        vector<string> cur;
        vectorbool> > dp(s.size(), vector<bool>(s.size(), false));
        getDP(dp, s);
        DFS(res, cur, s, 0, dp);
        return res;
    }
    
    void DFS(vectorstring> >& res, vector<string>& cur, string s, int start, vectorbool> >& dp)
    {
        if(start >= s.size())
        {
            res.push_back(cur);
            return ;
        }    
        for(int i = start; i < s.size(); i++)
        {
            if(dp[start][i]) 
            {
                cur.push_back(s.substr(start, i-start+1));
                DFS(res, cur, s, i+1, dp);
                cur.pop_back();
            }
        }
    }
    
    void getDP(vectorbool> >& dp, string s)
    {
        for(int i = 0; i < dp.size(); i++)
        {
            for(int j = i, k = 0; j < dp.size(); j++, k++)
            {
                if(abs(j-k) <= 1)
                    dp[k][j] = s[k] == s[j] ? true : false;
                else
                    dp[k][j] = (dp[k+1][j-1])&&(s[k] == s[j]);
            }
        }
    }
    
};

小白欢迎各位大神指点

 

转载于:https://www.cnblogs.com/yangzixiong/p/10742975.html

你可能感兴趣的:(131.leetcode-Palindrome Partitioning)