简体   繁体   English

使用数组中的前'n'个整数递归打印所有子集

[英]Recursively Print All Subsets Using First 'n' Integers in an Array

Recursively print the possible subsets using the first n integers of an array. 使用数组的前n个整数递归打印可能的子集。 Example: int[] X = [1, 2, 3, 4] and if n = 3, print [3, 2, 23, 1, 13, 12, 123] 示例:int [] X = [1,2,3,4],如果n = 3,则打印[3,2,23,1,13,12,123]

I've sat here for hours, I've tried blindly and am now turning to you guys for some help! 我已经在这里坐了几个小时,我已经盲目尝试,现在正在寻求你们的帮助! Here's what I have so far. 到目前为止,这就是我所拥有的。 Its nowhere near the answer so bear with me. 答案无处可寻,请耐心等待。

static void subsets(int[] A, int n){
    subsets("", A, n);
}
private static void subsets(String S, int[] A, int n){
    if(n == 0){
        System.out.println(S);
    } else {
        for (int i = n-1; i >= 0; i--) {
            subsets(A[n-i-1]+S, A, n-i);
        }
    }
}

There are many ways to solve this subsets problem, but I particularly like the one below. 有很多方法可以解决此子集问题,但我特别喜欢以下一种方法。

It relies on the fact that, when you count from 1 to N in binary (N being a power of 2) in binary, the bits get through all the possible unique combinations. 它依赖于以下事实:当您以二进制数从1到N计数(N是2的幂)时,这些位会经过所有可能的唯一组合。 So, if you "attach" each bit to a particular value in your array, you get every possible combinations of your values. 因此,如果将每个位“附加”到数组中的特定值,则将获得值的所有可能组合。

In your example, you take N = 3 values in your array. 在您的示例中,您在数组中取N = 3个值。 With N bits, you can get 2^3 (or 1<<3 ) = 8 different values. 使用N位,您可以获得2^3 (或1<<3 )= 8个不同的值。 So let's count from 0 to 7 in binary, and watch the bits that get on or off at each step : 因此,让我们以二进制数从0到7进行计数,并观察每个步骤中打开或关闭的位:

  • 1 = 001 -> take only the first item in your list 1 = 001->仅获取列表中的第一项
  • 2 = 010 -> take only the second item in your list 2 = 010->仅获取列表中的第二项
  • 3 = 011 -> ... 3 = 011-> ...
  • 4 = 100 4 = 100
  • 5 = 101 -> take the first and third elements in your list 5 = 101->选取列表中的第一和第三元素
  • 6 = 110 6 = 110
  • 7 = 111 7 = 111

And there you are : you found all possible subsets among your N elements. 在那里,您发现了N个元素中的所有可能子集。

Here is the code : 这是代码:

int[] nums = new int[]{1, 2, 3, 4};
int n = 3;

int maxValueOnNBits = 1 << n;

for (int i = 1; i <= maxValueOnNBits; i++) {
    for (int bit = 0; bit < n; bit++) {
        int mask = 1 << bit;
        if ((i & mask) == mask) System.out.print(nums[bit]);
    }
    System.out.println();
}

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

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