This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
arr=[5,4,8, 10,-4] | |
k=6 | |
def check_if_sum_possible(arr, k): | |
slate = [] | |
index = 0 | |
arrlen = 0 | |
if arr: | |
arrlen = len(arr) | |
def printSubset(index, slate): | |
#base case | |
if(index==arrlen): | |
sum = 0 | |
if slate: | |
for i in range(len(slate)): | |
sum = sum + slate[i] | |
if sum == k: | |
print(slate, end=" ") | |
return True | |
else: | |
return False | |
return | |
else: | |
return False | |
if(printSubset(index+1,slate)): | |
return True | |
slate.append(arr[index]) | |
if(printSubset(index+1,slate)): | |
return True | |
slate.pop() | |
if(printSubset(index,slate)): | |
return True | |
return False | |
print(check_if_sum_possible(arr, k)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<vector> | |
using namespace std; | |
vector<int> bag = { 2, 8, -2 }; | |
int sum = 6, index=0; | |
int bagSize; | |
bool flag = false; | |
bool printSubsetSums(int index , vector<int> slate){ | |
//basecase | |
if(index == bagSize){ | |
cout << endl; | |
int subsetSum = 0; | |
int sizeSlate = slate.size(); | |
for (auto i : slate){ | |
//cout << i << " "; | |
subsetSum = subsetSum + i; | |
} | |
if(subsetSum == sum){ | |
cout <<endl<<"sum found" <<endl; | |
for (auto i : slate){ | |
cout << i << " "; | |
} | |
flag = true; | |
return flag; | |
} | |
return flag; | |
} | |
//recursion | |
printSubsetSums(index+1 , slate); | |
slate.push_back(bag[index]); | |
printSubsetSums(index+1, slate); | |
slate.pop_back(); | |
} | |
int main(){ | |
cout<< "Subset sums"<<endl; | |
bagSize = bag.size(); | |
vector<int> slate ; | |
printSubsetSums(index, slate) ; | |
cout << std::boolalpha << flag; | |
} |