简体   繁体   English

递归地找到所有子集

[英]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. 假设您的字符串包含N个符号,并且每个符号都是唯一的。 Then to make subset we can include/exclude each symbol - that gives us 2 combination for one position; 然后,要制作子集,我们可以包含/排除每个符号-这样就可以为一个位置提供2种组合; with N symbols - we multiply them all and receive 2^N combinations. 使用N个符号-我们将它们全部相乘并接收2 ^ N个组合。

For example: abcd We can associate subsets {a,b,c} -> 1110; 例如:abcd我们可以关联子集{a,b,c}-> 1110; {a,d} -> 1001; {a,d}-> 1001; {b} -> 0100; {b}-> 0100; {} -> 0000; {}-> 0000; and so on 等等

1 << N - is bit operation that gives 2^N (or number with N bits) 1 << N-是给出2 ^ N(或N位数字)的位运算

(1 << j) - get 1 in j-th bit (1 << j)-在第j位获得1

(i & (1 << j)) - chech the j-th bit in number (i&(1 << j))-查数第j位

Also, this program is NOT recursive - it is linear and done with cycle 另外,该程序不是递归的-它是线性的,并用循环完成

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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