Tuesday, October 19, 2021

Subsets and Combinations generate using Backtracking

What are subsets?
Subsets are generating all possible subsequences in a given order. If there are N elements then possible subsets can be found 2^N.


Suppose given array is A[] = {1,2,3}, possible subsets is, {}, {1},{1,3}  etc total 2^3 = 8 subsets can generate, but {2,1} isn't a subset, because this one breaks the order.


We can solve this problem using backtracking. What can be our state? We need to traverse the array, so we need a position parameter, that's enough.

See the image, here we tried to illustrate the whole backtracking functions that generate all possible subsets.
So, what will be our operations, see every time we can pick the current value of the array or we can avoid the current value and move to forward.

Base case? if position reached the end of the array, we can simply add this subset to our answer, and return. 
 
Combinations:
Combinations are also the same as a subset, but here we just generate using fixed sizes subsets.

State same, we just have to modify base cases, Why?  because we have to generate k sizes subsets only and if position reached at the end of the array then simply we have to return from there. So, two base cases.


No comments:

Post a Comment