@(leetcode)[动态规划|Google]
Problem
Given a number N ( N > 1)
, gives a set S = [1,2,..., N]
.
Divide S in two subsets such that S1 ∪ S2 = S
and S1 ∩ S2 = Ø
and return the number of subsets with equal sum.
Example:
Given N = 7, S = [1, 2, 3, 4, 5, 6, 7]
. Return 2
, since sum of[1, 6, 7] = sum of [2, 3, 4, 5]
.
Solution
- 先求出数组的和sum
- 如果sum & 1 == 1, 返回0
- 否则就找出集合中和为 sum / 2的个数就是最终结果,背包问题
Code
int equal_sum_sub_set(vector<int>& num)
{
int sum = 0;
for(int n : num) {
sum += n;
}
if((sum & 1) == 1) {
return 0;
}
sum >>= 1;
vector<int> dp(sum + 1, 0);
dp[0] = 1;
int current_sum = 0;
for (int i = 0; i < num.size(); i++)
{
current_sum += num[i];
for (int j = min(sum, current_sum); j >= num[i]; j--)
dp[j] += dp[j - num[i]];
}
return dp[sum];
}