令dp[i][j]表示是否能从前i个数字中选出和为j的数, dp[i][j] = dp[i-1][j] || dp[i-1][j-nums[i]]
class Solution {
public:
bool canPartition(vector<int>& nums) {
int n = nums.size();
int total = accumulate(nums.begin(), nums.end(), 0);
if (total % 2 != 0)
return false;
int half = total / 2;
//dp[i][j]: 是否可以用前i个数字组成和为j
vector<vector<bool>> dp(n+1, vector<bool>(half + 1, false));
for (int i = 0; i <= n; ++i)
dp[i][0] = true;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= half + 1; ++j) {
if (dp[i-1][j]) {
dp[i][j] = true;
continue;
}
if (j - nums[i-1] >= 0 && dp[i-1][j-nums[i-1]])
dp[i][j] = true;
}
}
return dp[n][half];
}
};