C语言 | Leetcode C语言题解之第416题分割等和子集
题目:
题解:
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[target + 1];
memset(dp, 0, sizeof(dp));
dp[0] = true;
for (int i = 0; i < numsSize; i++) {
int num = nums[i];
for (int j = target; j >= num; --j) {
dp[j] |= dp[j - num];
}
}
return dp[target];
}