LintCode 1915. 举重(01背包)
生活随笔
收集整理的這篇文章主要介紹了
LintCode 1915. 举重(01背包)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
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. 解題
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 hereint 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++
我的CSDN博客地址 https://michael.blog.csdn.net/
長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LintCode 1915. 举重(01背包)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 774. 最小化去加油
- 下一篇: 天池 在线编程 布尔表达式求值(栈)