From 4d4077842c20d55d7eb34febc16cb56587228010 Mon Sep 17 00:00:00 2001 From: namishagoel <57214627+namishagoel@users.noreply.github.com> Date: Mon, 31 Oct 2022 22:17:29 +0530 Subject: [PATCH] Create SubetSumProblem.cpp --- SubetSumProblem.cpp | 42 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 SubetSumProblem.cpp diff --git a/SubetSumProblem.cpp b/SubetSumProblem.cpp new file mode 100644 index 0000000..ea0cb61 --- /dev/null +++ b/SubetSumProblem.cpp @@ -0,0 +1,42 @@ +// A recursive solution for subset sum problem +#include +using namespace std; + +// Returns true if there is a subset +// of set[] with sum equal to given sum +bool isSubsetSum(int set[], int n, int sum) +{ + + // Base Cases + if (sum == 0) + return true; + if (n == 0) + return false; + + // If last element is greater than sum, + // then ignore it + if (set[n - 1] > sum) + return isSubsetSum(set, n - 1, sum); + + /* else, check if sum can be obtained by any +of the following: + (a) including the last element + (b) excluding the last element */ + return isSubsetSum(set, n - 1, sum) + || isSubsetSum(set, n - 1, sum - set[n - 1]); +} + +// Driver code +int main() +{ + int set[] = { 3, 34, 4, 12, 5, 2 }; + int sum = 9; + int n = sizeof(set) / sizeof(set[0]); + if (isSubsetSum(set, n, sum) == true) + cout <<"Found a subset with given sum"; + else + cout <<"No subset with given sum"; + return 0; +} + +// This code is contributed by shivanisinghss2110