leetcode【每日抑题 416 分割等和子集】
程序员文章站
2024-03-09 07:58:10
...
bool canPartition(int* nums, int numsSize) {
if (numsSize < 2) {
return false;
}
int sum = 0, maxNum = 0;
for (int i = 0; i < numsSize; ++i) {
sum += nums[i];
maxNum = fmax(maxNum, nums[i]);
}
if (sum & 1) {
return false;
}
int target = sum / 2;
if (maxNum > target) {
return false;
}
int dp[numsSize][target + 1];
memset(dp, 0, sizeof(dp));
for (int i = 0; i < numsSize; i++) {
dp[i][0] = true;
}
dp[0][nums[0]] = true;
for (int i = 1; i < numsSize; i++) {
int num = nums[i];
for (int j = 1; j <= target; j++) {
if (j >= num) {
dp[i][j] = dp[i - 1][j] | dp[i - 1][j - num];
} else {
dp[i][j] = dp[i - 1][j];
}
}
}
return dp[numsSize - 1][target];
}
上一篇: Java单利模式与多线程总结归纳