ASSIGNMENT-7
A.PRATHIBA NAIDU
VU21CSEN0101484
1) Explain the code: // Function to find the subsets of the given array void
findSubsets(int nums[], int n) { // Loop through all possible subsets using bit
manipulation for (int i = 0; i < (1 << n); i++) { // Loop through all elements of the
input array for (int j = 0; j < n; j++) { // Check if the jth bit is set in the current subset
if ((i & (1 << j)) != 0) { // If the jth bit is set, add the jth element to the subset cout <<
nums[j] << " "; } } cout << endl; } }
Ans)The function findSubsets is designed to generate all possible subsets of an input
array using a method called bit manipulation. The function takes two parameters:
nums[], which is the input array, and n, the number of elements in the array. The
subsets are generated based on the binary representation of numbers, which helps
determine which elements should be included in each subset.
The outer loop of the function iterates from 0 to (1 << n) - 1, representing all possible
combinations of elements in the array. This range (from 0 to 2^n - 1) indicates every
subset that can be formed. Each number within this range serves as a binary mask,
where each bit (0 or 1) corresponds to whether a particular element from the input
array should be included in the subset.
The inner loop checks each bit of the integer i to determine if the corresponding
element in nums[] should be part of the current subset. This is done using the
expression (i & (1 << j)), where j is the index of the bit being checked. If the bit is set
(meaning it's a 1), it indicates that the element at index j in nums[] should be added to
the subset.
The subsets are then built element by element based on whether the bits in i are set. If
the bit for a particular index is set, the element at that index is added to the subset.
This continues until all elements have been checked for the current subset.
After building the subset for the current value of i, the function prints it. The function
iterates through all 2^ncombinations of elements, ensuring that every possible subset,
including the empty set and the full set containing all elements, is generated and
displayed.
This method efficiently uses bit manipulation to explore all subset combinations of
the input array. The approach ensures that the function operates in O(n * 2^n) time
complexity, which is suitable for small to moderate-sized arrays where all possible
subsets need to be considered.
2)Given an array Arr[] of size N, print all the subsets of the array.
3)Combination sum: Given a number n, find all valid combinations of k numbers that
sum up to n such that only numbers from 0 to 9 are used and each number is not used
more than once.
4)Phone number to alphabets: Given a string of digits from 2to9, write a function to
return all the possible strings that can be represented by the number, as per the
folloiwng mapping : 2- abc, 3 - def, 4 - ghi, 5 - jkl, 6 - mno, 7- pqr, 8 - stu, 9- wxyz