题目描述:
给定一个只包含正整数的非空数组。是否可以将这个数组分割成两个子集,使得两个子集的元素和相等。
注意:
- 每个数组中的元素不会超过 100
- 数组的大小不会超过 200
示例 1:
输入: [1, 5, 11, 5] 输出: true 解释: 数组可以分割成 [1, 5, 5] 和 [11].示例 2:
输入: [1, 2, 3, 5] 输出: false 解释: 数组不能分割成两个元素和相等的子集.
算法:
回溯法,深度优先搜索
class Solution {
public:
bool canPartition(vector<int>& nums) {
int value = 0;
for(auto& num: nums)
value += num;
if(nums.size()<1 || value %2 != 0)
return false;
vector<int>target(2, value / 2);
sort(nums.rbegin(), nums.rend());
return dfs(nums, 0, target);
}
bool dfs(vector<int>& nums, int index, vector<int>& target)
{
if(index == nums.size())
return true;
for(int i=0; i<2; i++)
{
if(target[i] - nums[index] >= 0)
{
target[i] -= nums[index];
if(dfs(nums, index + 1, target))
return true;
target[i] += nums[index];
}
}
return false;
}
};