LeetCode动态规划专题:第二十一天

这篇博客介绍了LeetCode上的两道算法题:组合总和IV和完全平方数。第一题中,通过动态规划求解在给定数组中找到所有可能的组合方式,使得它们的和等于目标值。第二题则探讨了如何确定一个整数是否为完全平方数,以及计算达到完全平方数所需的最小操作数。文章提供了详细的解题思路和代码实现。
摘要由CSDN通过智能技术生成

Leetcode377. 组合总和 Ⅳ

class Solution {
public:
    int combinationSum4(vector<int>& nums, int target) {
        vector<long long> f(target + 1);
        f[0] = 1;
        for (int j = 1; j <= target; j ++ )
            for (auto& x : nums) {
                if (j >= x) 
                    f[j] = (f[j] + f[j - x]) % INT_MAX;
            }
        return f[target];
    }
};

class Solution {
public:
    int integerBreak(int n) {
        if (n <= 3) return n - 1;
        else if (n == 4) return 4;
        else {
            if (n % 3 == 0) return pow(3, n / 3);
            else if (n % 3 == 1) return pow(3, n / 3 - 1) * 4;
            else return pow(3, n / 3) * 2;
        }
    }
};

279. 完全平方数

思路一:拉格朗日平方定理

class Solution {
public:
    bool check(int x) {
        int r = sqrt(x);
        return r * r == x;
    }
    int numSquares(int n) {
        if (check(n)) return 1;

        for (int a = 1; a <= n / a; a ++ ) {
            if (check(n - a * a))
                return 2;
        }

        while (n % 4 == 0) n /= 4;
        if (n % 8!= 7) return 3;
        return 4;
    }
};

思路二:动态规划背包问题

class Solution {
public:
    int numSquares(int n) {
        vector<int> f(n + 1);
        for (int i = 1; i <= n; i ++ ) f[i] = i;

        for (int i = 1; i * i <= n; i ++ ) {
            int v = i * i;
            for (int j = v; j <= n; j ++ )
                f[j] = min(f[j], f[j - v] + 1);
        }
        return f[n];
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Shirandexiaowo

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

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

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

打赏作者

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

抵扣说明:

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

余额充值