[Geeks for Geeks] Subset Sum Problem

Subset Sum Problem

Given an array of non-negative integers, and a value sum, determine if there is a subset of the given set with sum equal to given sum.

  • Time : O(nsum)
  • Space : O(sum)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
bool isSubsetSum(vector<int> arr, int sum) {
vector<bool> dp(sum + 1);
dp[0] = true;
for(auto& a : arr) {
for(int i = sum; i >= a and !dp[sum]; i--) {
if(dp[i-a]) dp[i] = true;
}
if(dp[sum]) break;
}

return dp[sum];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/20/PS/GeeksforGeeks/subset-sum-problem/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.