前往小程序,Get更优阅读体验!
立即前往
发布
社区首页 >专栏 >LintCode 1915. 举重(01背包)

LintCode 1915. 举重(01背包)

作者头像
Michael阿明
发布2021-02-19 14:13:26
发布2021-02-19 14:13:26
52600
代码可运行
举报
运行总次数:0
代码可运行

文章目录

1. 题目

奥利第一次来到健身房,她正在计算她能举起的最大重量。 杠铃所能承受的最大重量为maxCapacity,健身房里有 n 个杠铃片,第 i 个杠铃片的重量为 weights[i]。 奥利现在需要选一些杠铃片加到杠铃上,使得杠铃的重量最大,但是所选的杠铃片重量总和又不能超过 maxCapacity ,请计算杠铃的最大重量是多少。

比如,给定杠铃片的重量为 weights = [1, 3, 5], 而杠铃的最大承重为 maxCapacity = 7,那么应该选择重量为 1 和 5 的杠铃片,(1 + 5 = 6),所以最终的答案是 6。

https://www.lintcode.com/problem/lifting-weights/description

2. 解题

代码语言:javascript
代码运行次数:0
复制
class Solution {
public:
    /**
     * @param weights: An array of n integers, where the value of each element weights[i] is the weight of each plate i
     * @param maxCapacity: An integer, the capacity of the barbell
     * @return: an integer denoting the maximum capacity of items that she can lift.
     */
    int weightCapacity(vector<int> &weights, int maxCapacity) {
        // Write your code here
        int n = weights.size();
        vector<bool> dp(maxCapacity+1, false);
        dp[0] = true;
        int maxW = 0;
        for(int i = 0; i < n; ++i)
        {
            for(int j = maxCapacity-weights[i]; j>=0; --j)
            {	//逆序遍历,新状态不会干扰前面待遍历的旧状态
                if(dp[j])// j 重量状态存在
                {
                    dp[j+weights[i]] = true;
                    maxW = max(maxW, j+weights[i]);
                }
            }
        }
        return maxW;
    }
};

1307 ms C++


本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/02/03 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文章目录
  • 1. 题目
  • 2. 解题
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档