[InterviewBit] Subset Sum Problem!

Subset Sum Problem!

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int Solution::solve(vector<int> &A, int B) {
int sum = 0;
for(auto a : A) sum += a;
if(sum < B) return 0;
B = min(B, sum - B);
vector<int> dp(B + 1);
dp[0] = 1;
for(auto a : A) {
for(int i = dp.size() - 1; i >= a; i--) {
if(dp[i-a]) dp[i] = 1;
}
}

return dp[B];
}

Author: Song Hayoung
Link: https://songhayoung.github.io/2022/11/08/PS/Codeforces/subset-sum-problem/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.