01背包
经典动态规划问题,输入重量数组weight、价值数组value和背包可承载的最大重量整数maxW 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: int knapsack(vector<int>& weight, vector<int>& value, int maxW) { int kinds = weight.size(); vector<vector<int>> dp(kinds + 1, vector<int>(maxW + 1, 0)); for (int c = 1; c <= kinds; c++) { for (int w = 1; w <= maxW; w++) { if (w - weight[c - 1] < 0) dp[c][w] = dp[c - 1][w]; else dp[c][w] = max(dp[c - 1][w], dp[c - 1][w - weight[c - 1]] + value[c - 1]); } } return dp[kinds][maxW]; } };
|
标准DP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| class Solution { public: int change(int amount, vector<int>& coins) { int n = coins.size(); vector<vector<int>> dp(n+1, vector<int>(amount+1, 0)); for(int s = 0; s<=n; ++s) dp[s][0] = 1; for(int i=1; i<=n; ++i){ for(int j=1; j<=amount; ++j){ if(coins[i-1] > j) dp[i][j] = dp[i-1][j]; else dp[i][j] = dp[i-1][j] + dp[i][j-coins[i-1]]; } } return dp[n][amount]; } };
|
压缩一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| class Solution { public: int change(int amount, vector<int>& coins) { int n = coins.size(); vector<int> dp(amount+1, 0); dp[0] = 1; for(int i=1; i<=n; ++i){ for(int j=1; j<=amount; ++j){ if(coins[i-1] <= j) dp[j] = dp[j] + dp[j-coins[i-1]]; } } return dp[amount]; } };
|
标准DP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| class Solution { public: bool canPartition(vector<int>& nums) { int sum = 0; for (auto e : nums) sum += e; if (sum % 2) return false; int target = sum >> 1; int n = nums.size(); vector<vector<bool>> dp(n + 1, vector<bool>(target + 1, 0)); dp[0][0] = 1; for (int i = 1; i <= n; i++) { for (int j = 0; j <= target; j++) { if (nums[i - 1] > j) dp[i][j] = dp[i - 1][j]; else dp[i][j] = dp[i - 1][j] + dp[i - 1][j - nums[i - 1]]; } } return dp[n][target] > 0; } };
|
压缩一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| class Solution { public: bool canPartition(vector<int>& nums) { int sum = 0; for (auto e : nums) sum += e; if (sum % 2) return false; int target = sum >> 1; int n = nums.size(); vector<bool> dp(target + 1, false); dp[0] = true; for (int i = 1; i <= n; i++) { for (int j = target; j >= 0; j--) { if (nums[i - 1] > j) dp[j] = dp[j]; else dp[j] = dp[j] || dp[j - nums[i - 1]]; } } return dp[target] > 0; } };
|
参考
labuladong