LintCode 749: John's backyard garden (完全背包题变种)

本文探讨了一个有趣的算法问题,即如何使用两种不同高度的砖块(3dm和7dm)来构建任意高度的围墙。通过一个完全背包变种算法的实现,我们能够判断是否可以使用这些砖块构建出特定高度的围墙。本文提供了详细的算法思路及代码实现,为读者展示了如何解决此类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. John’s backyard garden

John wants to build a back garden on the empty space behind his home. There are two kinds of bricks now, one is 3 dm high and the other is 7 dm high. John wants to enclose a high x dm wall. If John can do this, output YES, otherwise NO.

Example
Example 1:

Input : x = 10
Output : “YES”
Explanation :
x = 3 + 7:That is, you need one batch of 3 dm height bricks and one batch of 7 dm height bricks.
Example 2:

Input : x = 5
Output : “NO”
Explanation:
John can not enclose a high 5 dm wall with 3 dm height bricks and 7 dm height bricks.
Example 3:

Input : x = 13
Output : “YES”
Explanation :
x = 2 * 3 + 7:That is, you need two batch of 3 dm height bricks and one batch of 7 dm height bricks.
Notice
X is an integer, and it’s range is [3, 1000].

解法1:完全背包变种。
代码如下:

class Solution {
public:
    /**
     * @param x: the wall's height
     * @return: YES or NO
     */
    string isBuild(int x) {
        string result;
        vector<int> A = {3, 7};
        vector<int> dp(x + 1, 0);
        dp[0] = 1;
        for (int i = 0; i <= 1; ++i) {
            for (int j = A[i]; j <= x; ++j) {
                dp[j] = dp[j] || dp[j - A[i]];
            }    
        }
        
        if (dp[x]) return "YES";
        else return "NO";
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值