[英]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.