简体   繁体   中英

recursively finding all subsets

I don't know how this code works,can you please explain about it

// A Java program to print all subsets of a set
import java.io.IOException;
import java.util.Scanner;
class Main
{
    // Print all subsets of given set[]
    static void printSubsets(char set[])
    {
        int n = set.length;

        // Run a loop for printing all 2^n
        // subsets one by one
        for (int i = 0; i < (1<<n); i++)
        {
            System.out.print("{ ");

            // Print current subset
            for (int j = 0; j < n; j++)

                // (1<<j) is a number with jth bit 1
                // so when we 'and' them with the
                // subset number we get which numbers
                // are present in the subset and which
                // are not
                if ((i & (1 << j)) > 0)
                    System.out.print(set[j] + " ");

            System.out.println("}");
        }
    }

    // Driver code
    public static void main(String[] args)
    {   Scanner in = new Scanner(System.in);
    char[] set = in.nextLine().replaceAll("[?!^]","").toCharArray();
    //char[] set = in.nextLine().split("(?!^)").toCharArray();
        //char set[] = {'a', 'b', 'c'};
        printSubsets(set);
        in.close();
    }
}

and basically I can't think recursively and I have problem with it, if there is anything I can do please tell me

This code prints all subsets of symbols. Let assume your string conatins N symbols and each symbol is unique. Then to make subset we can include/exclude each symbol - that gives us 2 combination for one position; with N symbols - we multiply them all and receive 2^N combinations.

For example: abcd We can associate subsets {a,b,c} -> 1110; {a,d} -> 1001; {b} -> 0100; {} -> 0000; and so on

1 << N - is bit operation that gives 2^N (or number with N bits)

(1 << j) - get 1 in j-th bit

(i & (1 << j)) - chech the j-th bit in number

Also, this program is NOT recursive - it is linear and done with cycle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM