Complementary task for topic: 10

M Nemeth · 2023-08-29 15:21:04.633218'

Recursion: Combination II.

Recursion: Combination II.

Write a program to generate all possible subsets of a set using recursion. A subset is a set that contains elements from the original set but may not include all elements.

Hint: Like combination of strings

Solution
#include 

// Function to generate all possible subsets of a set using recursion
void generateSubsets(int set[], int n, int subset[], int index) {
    if (index == n) {
        // Base case: Print the current subset
        printf("{ ");
        for (int i = 0; i < n; i++) {
            if (subset[i] == 1) {
                printf("%d ", set[i]);
            }
        }
        printf("}\n");
        return;
    }

    // Include the element at the current index in the subset
    subset[index] = 1;
    generateSubsets(set, n, subset, index + 1);

    // Exclude the element at the current index from the subset
    subset[index] = 0;
    generateSubsets(set, n, subset, index + 1);
}

int main() {
    int n;
    printf("Enter the number of elements in the set: ");
    scanf("%d", &n);

    if (n <= 0) {
        printf("Error: The number of elements should be greater than 0.\n");
        return 1;
    }

    int set[n];
    printf("Enter %d elements of the set:\n", n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &set[i]);
    }

    int subset[n]; // Array to store the current subset
    printf("All possible subsets of the set:\n");
    generateSubsets(set, n, subset, 0);

    return 0;
}



Explanation

< < previous    next > >