1. 程式人生 > 其它 >LintCode 1915. 舉重(01揹包)

LintCode 1915. 舉重(01揹包)

技術標籤:LintCode及其他OJ

文章目錄

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 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++


我的CSDN部落格地址 https://michael.blog.csdn.net/

長按或掃碼關注我的公眾號(Michael阿明),一起加油、一起學習進步!
Michael阿明