Trying for any one combination first

#include
#include

using namespace std;

//problem: considering one number for only one combination

bool sum_it_up(vectorv, vectorans, int i, int sum, int k){

if(k>sum || i==v.size()){
return false;
}

if(k==sum){
//print the ans vector

for(auto x:ans){
	cout<<x<<" ";
}

cout<<endl;

//since we need all the combinations
return true;

}

//recursive call for considering numbers

for(int number=i; number<v.size(); number++){

//consider we can take this number and its ok
ans.push_back(v[number]);

bool sum_lies_ahead= sum_it_up(v,ans,number+1,sum,k+v[number]);

if(sum_lies_ahead==true){
	return true;
}

ans.pop_back(); //backtrack,if not

}

return false;
}

int main(){

vector<int>v;

int n;

cin>>n;

for(int i=0; i<n; i++){

	int no;
	cin>>no;
	v.push_back(no);

}

vector<int>ans;

sum_it_up(v,ans,0,6,0);

return 0;
}

THIS WAS THE PROBLEM:
I am first trying to check for 1 combination only. (I’ll handle the duplicates and other combinations later on)
The error is: If the first element isn’t included in the combination it isn’t showing any combination.
Example
5
1 0 5 7 8
It is showing 1,5
whereas if
5
0 1 6 5 7
It isn’t showing anything

@aman212yadav please check bro


pls save u code here.
ans share the link with me,

@aman212yadav

@aman212yadav please check!

so sorry brother, i missed ur doubt by mistake.

pls check the link that u shared,it is not correct

it is working na?

output is correct.
sum 6 = 0+1+5

checck ur corrected code.

ther is no need of loop.

at each index i. we have two option .
eitherr we discard it .
or we include it.
so we just have to make two call.
one by including i and one by discarding i.
thats it

I don’t know how! It wasn’t working earlier :expressionless:

But aren’t we trying to go beyond index i everytime to search for an answer.
suppose currently I am on index i with arr[i]=5, to search for 1 won’t I go to i+1 to n

yeah we make A call to i+1 by then k > sum

and from base case it will return falsr.

so it will not propagate furthur

Did not understand why did you add bool sum_lies_ahead= sum_it_up(v,ans,i+1,sum,k);

that is a first case when we are not including i in our answer

1 Like

Basically we are just trying to generate all the subsequences?

correct… …

1 Like

can you explain me why my initial approach was incorrect and skipping some subsequences? (when k==sum returned false and we tried to generate all the possible answers?)

For reference.
it is skipping 1 2 5

just remove that return statement …and then try

Not working infact the new code that you edited is missing 12 5 too