I am trying to print all possible sub array from define list. For doing that I am using below code
static void printSubArray(int arr[]) {
int n = arr.length;
for (int i = 0; i < n; i ) {
for (int j = i; j < n; j ) {
for (int k = i; k <= j; k ) {
System.out.print(arr[k] " ");
}
System.out.println();
}
}
}
Tried above code some extend its working but not printing all the possible array. For example please find below example:
Input:: int a[] = { 1, 2, 3 };
Output::
1
1 2
1 2 3
2
2 3
3
As we can see in the output few of the subarray is missing like 1, 3.
Can some one please help on this
CodePudding user response:
There is a difference betweek subarray and subsequence {1,3} is not a subarray . It has to be continuous
Read the below article https://www.geeksforgeeks.org/subarraysubstring-vs-subsequence-and-programs-to-generate-them/
CodePudding user response:
So a current number should be printed in its line, then it is excluded and all the following numbers are printed, with the current number passed on as a prefix to be included in further printings.
The number of sets is 2n - 1, where n
is the length of the input array.
Thus, the following recursive solution can be developed:
static void printSubArray(int ... arr) {
printSubArray("", -1, arr);
}
static void printSubArray(String prefix, int ix, int ... arr) {
for (int i = ix 1; i < arr.length; i ) {
System.out.println(prefix arr[i]);
printSubArray(prefix arr[i] " ", i, arr);
}
}
For the input printSubArray(1, 2, 3)
it prints:
1
1 2
1 2 3
1 3
2
2 3
3
For the input printSubArray(1, 2, 3, 4)
it prints:
1
1 2
1 2 3
1 2 3 4
1 2 4
1 3
1 3 4
1 4
2
2 3
2 3 4
2 4
3
3 4
4