add solution2

This commit is contained in:
ShusenTang 2019-11-25 23:26:57 +08:00 committed by GitHub
parent e42c603dfd
commit 90575b6745
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -13,7 +13,7 @@
## 思路二
其实本题也可以看做是一个01背包问题改天对背包问题做个总结先占个坑
其实本题也可以看做是一个恰好装满的01背包问题我在我的博客文章[动态规划之背包问题系列](https://tangshusen.me/2019/11/24/knapsack-problem/)对常见的几类背包问题做了个总结此题的分析见5.1节,这里只给出代码
# C++
@ -30,3 +30,21 @@ public:
}
};
```
## 思路二
``` C++
bool canPartition(vector<int>& nums) {
int sum = 0, n = nums.size();
for(int &num: nums) sum += num;
if(sum % 2) return false;
int capacity = sum / 2;
vector<bool>dp(capacity + 1, false);
dp[0] = true;
for(int i = 1; i <= n; i++)
for(int j = capacity; j >= nums[i-1]; j--)
dp[j] = dp[j] || dp[j - nums[i-1]];
return dp[capacity];
}
```