代码随想录算法训练营第31天 | 第九章 动态规划04

avatar
作者
猴君
阅读量:0

文章目录


今日记录


1049.最后一块石头的重量II

Leetcode链接

class Solution { public:     int lastStoneWeightII(vector<int>& stones) {         vector<int> dp(15001, 0);         int sum = 0;         for (int i = 0; i < stones.size(); i++) {             sum += stones[i];         }         int target = sum / 2; // 向下取整         for (int i = 0; i < stones.size(); i++) {             for (int j = target; j >= stones[i]; j--) {                 dp[j] = max(dp[j], dp[j - stones[i]] + stones[i]);             }         }         return sum - dp[target] - dp[target];     } }; 

494. 目标和

Leetcode链接

class Solution { public:     int findTargetSumWays(vector<int>& nums, int target) {         int sum = 0;         for (int i = 0; i < nums.size(); i++) {             sum += nums[i];         }         if ((sum + target) % 2 == 1)             return 0;         if (abs(target) > sum)             return 0;         int bagsize = (sum + target) / 2;         vector<int> dp(bagsize + 1, 0);         dp[0] = 1;         for (int i = 0; i < nums.size(); i++) {             for (int j = bagsize; j >= nums[i]; j--) {                 dp[j] += dp[j - nums[i]];             }         }         return dp[bagsize];     } }; 

474.一和零

Leetcode链接

class Solution { public:     int findMaxForm(vector<string>& strs, int m, int n) {         vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));         for (string str : strs) {             int oneNum = 0;             int zeroNum = 0;             for (char c : str) {                 if (c == '0')                     zeroNum++;                 else                     oneNum++;             }             for (int i = m; i >= zeroNum; i--) {                 for (int j = n; j >= oneNum; j--) {                     dp[i][j] = max(dp[i][j], dp[i - zeroNum][j - oneNum] + 1);                 }             }         }         return dp[m][n];     } }; 

总结

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!