繁体   English   中英

递归地找到所有子集

[英]recursively finding all subsets

我不知道此代码的工作原理,请您解释一下

// 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();
    }
}

基本上我无法递归思考,对此我有疑问,如果有什么我可以做的,请告诉我

此代码打印符号的所有子集。 假设您的字符串包含N个符号,并且每个符号都是唯一的。 然后,要制作子集,我们可以包含/排除每个符号-这样就可以为一个位置提供2种组合; 使用N个符号-我们将它们全部相乘并接收2 ^ N个组合。

例如:abcd我们可以关联子集{a,b,c}-> 1110; {a,d}-> 1001; {b}-> 0100; {}-> 0000; 等等

1 << N-是给出2 ^ N(或N位数字)的位运算

(1 << j)-在第j位获得1

(i&(1 << j))-查数第j位

另外,该程序不是递归的-它是线性的,并用循环完成

暂无
暂无

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

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