Algorithms – Faster Algorithm for Finding All Subsets

algorithms

This is the algorithm (pseudocode) I have right now for finding all subsets for a given set with length k:

void allSubsets(set[]) {
    for (i = 0; i<k; i++) {
        for (j = i + 1; j<k; j++) {
            print(set[i...j]);
        }
    }
}

But it's run-time is O(n^2). Can anybody improve this?

Best Answer

From what I understand this doesn't work. You wouldn't find "AC" in the set "ABCD" (i.e. holes). To find all subsets think that each element is either inside the subset or not. Which is basically a binary yes, no. Therefore you can cycle over all numbers with k 0/1 bits to find all combinations.

Related Topic