Sum it Up problem

In line 41 of the code i have used a sort function to sort the input vector , due to which i got correct answer but if instead of writing sort function in line 41 , if i sort the subset vector and insert into set as done in line 14 , i am getting a wrong output ? Can u please explain

Hi @ujj1804_1156aee80205d0bf
It’s evident that sorting in line 14, u will get wrong ans… reason being u are using the subset vector for storing the subsets and later due to backtracking u pop that element… but now when u sort the subset vector, element at last position gets relocated and some other element gets popped instead of the actual one… Hence it results in wrong ans…
Hope it clears your doubt…

So basically, i sorted the subset array and due to pass by reference concept my old subset is no longer and hence backtracking would not give us correct older subsets for next recursive call .

right?

yes, if u want to perform that sorting in that base case only, so maybe u can use a temporary vector, assign it with subset vector, sort it and then insert it in set, instead of performing the sort function directly on subset vector…

Thanks sir , it worked , i wanted to ask that as in the code i inserted the subsets in a set of vectors , and then pushedback the subsets from the set into a vector of vectors to check if(sum==target) and display those subsets , is there any way that we can directly check the same in the set only without using a vector of vector ?

yes @ujj1804_1156aee80205d0bf
u can directly traverse over the set like this -->

        for(auto x:obj){
            int sum = 0;
            for(auto y:x){
                sum += y;
            }
            if(sum == Target && x.size() != 0){
                for(auto y:x){
                    cout<<y<<" ";
                }
                cout<<endl;
            }
        }

THANK YOU VERY MUCH SIR. DOUBT CLEAR.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

Sir the feedback form is not working when i click it only a white page comes. Please send another link i will give the feedback.

Actually its a auto generated link, so i cant send another link… no worries if its not working…