【力扣系列题目】最后一块石头的重量 分割回文串 验证回文串 等差数列划分{最大堆 背包 动态规划}


在这里插入图片描述

七、最后一块石头的重量

最后一块石头的重量【堆】

class Solution {
   
public:
    int lastStoneWeight(vector<int>& stones) {
   
        priority_queue<int> q;
        for (int s : stones) {
   
            q.push(s);
        }

        while (q.size() > 1) {
   
            int a = q.top();
            q.pop();
            int b = q.top();
            q.pop();
            if (a > b) {
   
                q.push(a - b);
            }
        }
        return q.empty() ? 0 : q.top();
    }
};

最后一块石头的重量 II【背包】

class Solution {
   
public:
    int lastStoneWeightII(vector<int>& stones) {
   
        int sum = 0;
        for (auto x : stones)
            sum += x;
        int n = stones.size(), m = sum / 2;
        vector<vector<int>> dp(n + 1, vector<int>(m + 1));
        for (int i = 1; i <= n; i++) {
   
            for (int j = 0; j <= m; j++) {
   
                dp[i][j] = dp[i - 1][j];
                if (j >= stones[i - 1])
                    dp[i][j] = max(dp[i][j], dp[i - 1][j - stones[i - 1]] +
                                                 stones[i - 1]);
            }
        }

        return sum - 2 * dp[n][m];
    }
};

八、分割回文串

分割回文串【分割子串方案数量】

class Solution {
   
private:
    vector<vector<int>> f;
    vector<vector<string>> ans;
    vector<string> path;
    int n;

    void dfs(const string& s, int i) {
   
        if (i == n) {
   
            ans.push_back(path);
            return;
        }
        for (int j = i; j < n; ++j) {
   
            if (isPalindrome(s, i, j) == 1) {
   
                path.push_back(s.substr(i, j - i + 1));
                dfs(s, j + 1);
                path.pop_back();
            }
        }
    }

    // 0未搜索 1回文串 -1不是回文串
    int isPalindrome(const string& s, int i, int j) {
   
        if (f[i][j] != 0)
            return f[i][j];

        if (i > j || i == j || (i + 1 == j && s[i] == s[j]))
            return f[i][j] = 1;
        f[i][j] = (s[i] == s[j] ? isPalindrome(s, i + 1, j - 1) : -1);
        return f[i][j];
    }

public:
    vector<vector<string>> partition(string s) {
   
        n = s.size();
        f.assign(n, vector<int>(n));

        dfs(s, 0);
        return ans;
    }
};

分割回文串 II【最少分割次数】

class Solution
{
   
    void init(const string &s, vector<vector<bool>> &isPal)
    {
   
        int n = s.size();
        for (int i = n - 1; i >= 0; i--)
        {
   
            for (in
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

阿猿收手吧!

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值