From 4f7c2698135d0c6ff6142783665be64932e74de2 Mon Sep 17 00:00:00 2001 From: ashishkore <43812466+ashishkore@users.noreply.github.com> Date: Wed, 3 Oct 2018 16:55:44 +0530 Subject: [PATCH] Subsetsum --- dynamic_programming/subsetsum.cpp | 36 +++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 dynamic_programming/subsetsum.cpp diff --git a/dynamic_programming/subsetsum.cpp b/dynamic_programming/subsetsum.cpp new file mode 100644 index 0000000..f36b1af --- /dev/null +++ b/dynamic_programming/subsetsum.cpp @@ -0,0 +1,36 @@ + +// A recursive solution for subset sum problem +#include + +// Returns true if there is a subset of set[] with sun equal to given sum +bool isSubsetSum(int set[], int n, int sum) +{ + // Base Cases + if (sum == 0) + return true; + if (n == 0 && sum != 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 program to test above function +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) + printf("Found a subset with given sum"); + else + printf("No subset with given sum"); + return 0; +}