Find number of subsets with equal sum

73 篇文章 1 订阅
8 篇文章 0 订阅

@(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

  1. 先求出数组的和sum
  2. 如果sum & 1 == 1, 返回0
  3. 否则就找出集合中和为 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];
}
This is a classic problem of finding the number of subsets of a given set with a certain property. In this case, we want to find the number of subsets of the set {0,1,2,...,k-1} such that the sum of the elements in the subset is less than or equal to n. We can use dynamic programming to solve this problem efficiently. Let dp[i][j] be the number of ways to choose a subset of the first i elements of the set {0,1,2,...,k-1} such that the sum of the elements in the subset is exactly j. Then the answer to the problem is the sum of dp[k][0] to dp[k][n]. The base case is dp[0][0]=1, since there is exactly one way to choose an empty subset with sum zero. For each i from 1 to k, we can either choose the i-th element or not. If we choose it, then we need to find the number of ways to choose a subset of the first i-1 elements with sum j-2i. If we do not choose it, then we need to find the number of ways to choose a subset of the first i-1 elements with sum j. Therefore, dp[i][j] = dp[i-1][j] + dp[i-1][j-2i], if j>=2i dp[i][j] = dp[i-1][j], otherwise The final answer is the sum of dp[k][0] to dp[k][n]. The time complexity of this algorithm is O(kn). Here is the Python code to solve the problem: ```python t = int(input()) for _ in range(t): n, k = map(int, input().split()) dp = [[0] * (n+1) for _ in range(k+1)] dp[0][0] = 1 for i in range(1, k+1): for j in range(n+1): dp[i][j] = dp[i-1][j] if j >= 2**i: dp[i][j] += dp[i-1][j-2**i] print(sum(dp[k])) ``` I hope this helps! Let me know if you have any more questions.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值