Check in (12)

class Solution {
    
    
private:
    vector<vector<int>> f;//类似于KMP的失败函数
    int n;//n代表的是一个n的值
    int ans_num;
    int anstemp=0;
public:
    void dfs(const string& s, int i){
    
    
        if(i==n){
    
    
            if(ans_num>anstemp&&anstemp!=0) ans_num=anstemp;
            return;
        }
        for(int j = i; j < n; ++j) {
    
    
            if(f[i][j]){
    
    //若当前是回文串,则进行下一轮递归
                anstemp++;
                dfs(s, j + 1);//继续递归
                anstemp--;
            }
        }
    }
    int minCut(string s){
    
    
        n = s.size();
        ans_num=n;
        f.assign(n, vector<int>(n, true));//初始化全部为true
        for(int i = n - 1; i >= 0; --i){
    
    
            for(int j = i + 1; j < n; ++j){
    
    
                f[i][j] = (s[i] == s[j]) && f[i + 1][j - 1];//动态规划,然后得到所有的dp值
            }
        }
        if(f[0][n-1]) return 0;
        dfs(s, 0);
        if(ans_num==0) return 0;
        else return ans_num-1;//返回答案
    }
};

Give a timeout code.
https://leetcode-cn.com/problems/palindrome-partitioning-ii/submissions/
When the difficulty of the question reaches hard, I can only smile.

class Solution {
    
    
public:
    int minCut(string s) {
    
    
        int n = s.size();
        vector<vector<int>> g(n, vector<int>(n, true));
        for (int i = n - 1; i >= 0; --i) {
    
    
            for (int j = i + 1; j < n; ++j) {
    
    
                g[i][j] = (s[i] == s[j]) && g[i + 1][j - 1];
            }
        }
        vector<int> f(n, INT_MAX);
        for (int i = 0; i < n; ++i) {
    
    
            if (g[0][i]) {
    
    
                f[i] = 0;//若整体为回文串,则直接赋值
            }
            else {
    
    
                for (int j = 0; j < i; ++j) {
    
    
                    if(g[j + 1][i]){
    
    //从j开始动态规划了,也就是要充分使用前面得出的所有动态规划的结果。
                    //从前向后看其实是有点贪心的成分在里面
                    //从后向前看,即这个代码的合理解释是,观察的重点是最后一个分割出来的回文串,则就是包括了所有的可能性了
                    //其实就是在穷举所有的可能的最后一个回文串,由于必定有单位字符串的存在,那么久一定有数值存在,所以不必担心什么特殊情况的排除
                        f[i] = min(f[i], f[j] + 1);
                    }
                }
            }
        }
        return f[n - 1];
    }
};

Looking at it this way, maybe in the past, many dynamic programming were regarded as greedy.
Harm, the understanding is not deep, just increase the laughter. Reduce a bit of hostility and go for machine learning.
Therefore, foreign textbooks are better. The Chinese pride themselves on being geniuses, so the textbooks compiled can only be understood by geniuses.
Huhuuhu, ridiculous and ridiculous.

Guess you like

Origin blog.csdn.net/weixin_47741017/article/details/114555753