Recursively print the possible subsets using the first n integers of an array. Example: int[] X = [1, 2, 3, 4] and if n = 3, print [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. 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. With N bits, you can get 2^3
(or 1<<3
) = 8 different values. So let's count from 0 to 7 in binary, and watch the bits that get on or off at each step :
And there you are : you found all possible subsets among your N elements.
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();
}
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.