//
// main.cpp
// Subset with given sum
//
// Created by Himanshu on 18/09/21.
//
#include <iostream>
using namespace std;
const int N = 7;
int solve (int A[], int sum) {
int dp[sum+1][N+1];
// Zero sum is possible with empty subset
for (int i=0; i<=N; i++) {
dp[0][i] = 1;
}
// If subset is empty then any sum
// greater than 0 is not possible
for (int i=1; i<=sum; i++) {
dp[i][0] = 0;
}
for (int i=1; i<=sum; i++) {
for (int j=1; j<=N; j++) {
dp[i][j] = dp[i][j-1];
if (i >= A[j-1]) {
dp[i][j] = dp[i][j] + dp[i-A[j-1]][j-1];
}
}
}
return dp[sum][N];
}
int main() {
int A[N] = {5, 3, 4, 6, 8, 11, 20};
int sum = 15;
if (solve(A, sum) != 0) {
cout<<"Subset with sum "<<sum<<" is present"<<endl;
} else {
cout<<"No subset with given sum "<<sum<<" is present"<<endl;
}
sum = 60;
if (solve(A, sum) != 0) {
cout<<"Subset with sum "<<sum<<" is present"<<endl;
} else {
cout<<"No subset with given sum "<<sum<<" is present"<<endl;
}
}
Ly8KLy8gIG1haW4uY3BwCi8vICBTdWJzZXQgd2l0aCBnaXZlbiBzdW0KLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMTgvMDkvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7CmNvbnN0IGludCBOID0gNzsKCmludCBzb2x2ZSAoaW50IEFbXSwgaW50IHN1bSkgewogICAgaW50IGRwW3N1bSsxXVtOKzFdOwogICAgCiAgICAvLyBaZXJvIHN1bSBpcyBwb3NzaWJsZSB3aXRoIGVtcHR5IHN1YnNldAogICAgZm9yIChpbnQgaT0wOyBpPD1OOyBpKyspIHsKICAgICAgICBkcFswXVtpXSA9IDE7CiAgICB9CiAgICAKICAgIC8vIElmIHN1YnNldCBpcyBlbXB0eSB0aGVuIGFueSBzdW0KICAgIC8vIGdyZWF0ZXIgdGhhbiAwIGlzIG5vdCBwb3NzaWJsZQogICAgZm9yIChpbnQgaT0xOyBpPD1zdW07IGkrKykgewogICAgICAgIGRwW2ldWzBdID0gMDsKICAgIH0KICAgIAogICAgZm9yIChpbnQgaT0xOyBpPD1zdW07IGkrKykgewogICAgICAgIGZvciAoaW50IGo9MTsgajw9TjsgaisrKSB7CiAgICAgICAgICAgIGRwW2ldW2pdID0gZHBbaV1bai0xXTsKICAgICAgICAgICAgaWYgKGkgPj0gQVtqLTFdKSB7CiAgICAgICAgICAgICAgICBkcFtpXVtqXSA9IGRwW2ldW2pdICsgZHBbaS1BW2otMV1dW2otMV07CiAgICAgICAgICAgIH0KICAgICAgICB9CiAgICB9CiAgICAKICAgIHJldHVybiBkcFtzdW1dW05dOwogICAgCn0KIAppbnQgbWFpbigpIHsKICAgIGludCBBW05dID0gezUsIDMsIDQsIDYsIDgsIDExLCAyMH07CiAgICBpbnQgc3VtID0gMTU7CiAgICBpZiAoc29sdmUoQSwgc3VtKSAhPSAwKSB7CiAgICAgICAgY291dDw8IlN1YnNldCB3aXRoIHN1bSAiPDxzdW08PCIgaXMgcHJlc2VudCI8PGVuZGw7CiAgICB9IGVsc2UgewogICAgICAgIGNvdXQ8PCJObyBzdWJzZXQgd2l0aCBnaXZlbiBzdW0gIjw8c3VtPDwiIGlzIHByZXNlbnQiPDxlbmRsOwogICAgfQogICAgCiAgICBzdW0gPSA2MDsKICAgIGlmIChzb2x2ZShBLCBzdW0pICE9IDApIHsKICAgICAgICBjb3V0PDwiU3Vic2V0IHdpdGggc3VtICI8PHN1bTw8IiBpcyBwcmVzZW50Ijw8ZW5kbDsKICAgIH0gZWxzZSB7CiAgICAgICAgY291dDw8Ik5vIHN1YnNldCB3aXRoIGdpdmVuIHN1bSAiPDxzdW08PCIgaXMgcHJlc2VudCI8PGVuZGw7CiAgICB9Cn0K