Backtracking to find all subsets
There is a set contains N number of elements. You have to find out all the possible subsets of the given set and print them.
Input:
Test case T
//T no. of lines with the value of N and corresponding values.
E.g.
2
4
1 2 3 4
2
7 8
1<=T<=100
1<=N<=1000
Output:
Print the subsets of the set.
Example
T=2
Input:
N=4
1 2 3 4
Output:
1 2
1 2 3
1 2 3 4
1 2 4
1 3
1 3 4
1 4
2
2 3
2 3 4
2 4
3
3 4
4
Input:
N=2
7 8
Output:
7
7 8
8
Let, there is a Set S having N number of elements,
S = {X1, X2, X3, ..., Xn}The process to print the subsets of the set is a problem of combination and permutation. To get the result we use the backtracking process.
Let, f(i) = function to insert the ith number into a subset.Here, we take a subset of that set in our consideration and consider two things,
For: N=3 S = { 1 2 3 }Algorithm:
Here we use the vector STL to store the subsets.
traverse(arr, n, current_pos,set,subset){ if(Current_pos is greater or equals to the n)Then return end if for i = current_pos to the end of the set insert the element of arr[i] into subset insert the subset into the set traverse(arr,n,i+1,set,subset) pop the element from subset end for }C++ implementation:
Output
need an explanation for this answer? contact us directly to get an explanation for this answer