回溯法——20191230

4 leetcode.416分割等和字符串
4.1 题目描述
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
注意:
每个数组中的元素不会超过 100
数组的大小不会超过 200

示例 1:
输入: [1, 5, 11, 5]
输出: true
解释: 数组可以分割成 [1, 5, 5] 和 [11].

示例 2:
输入: [1, 2, 3, 5]
输出: false
解释: 数组不能分割成两个元素和相等的子集.
4.2 代码
//通过设置两个数tmpSum1和tmpSum2,分开加就可以区分取不取当前的数
//使用index,而不是nums[0],这样就不用给给地址+1,节省了+1的时间
bool canPart(int* nums, int index, int sum, int tmpSum1, int tmpSum2) {
if(index < 0 || tmpSum1 > sum || tmpSum2 > sum) { //剪枝

    return false;
}

if(tmpSum1 == sum || tmpSum2 == sum) {
    return true;
}

return canPart(nums, index - 1, sum, tmpSum1, tmpSum2 + nums[index]) || canPart(nums, index - 1, sum, tmpSum1 + nums[index], tmpSum2);

}

bool canPartition(int* nums, int numsSize) {
int sum = 0;
int i = 0, j = 0;
for(i = 0; i < numsSize; i++) {
sum += nums[i];
}
if(sum % 2 != 0) {
return false;
}

sum = sum / 2;

return canPart(nums, numsSize - 1, sum, 0, 0);

}

发布了39 篇原创文章 · 获赞 1 · 访问量 856

猜你喜欢

转载自blog.csdn.net/weixin_42268479/article/details/103772686
今日推荐