Subarray/Substring vs Subsequence and Programs to Generate them - GeeksforGeeks
A subbarray is a contiguous part of array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subbarays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4). In general, for an array/string of size n, there are n*(n+1)/2 non-empty subarrays/subsrings.
How to generate all subarrays?
We can run two nested loops, the outer loop picks starting element and inner loop considers all elements on right of the picked elements as ending element of subarray.
A subsequence is a sequence that can be derived from another sequence by zero or more elements, without changing the order of the remaining elements.
For the same example, there are 15 sub-sequences. They are (1), (2), (3), (4), (1,2), (1,3),(1,4), (2,3), (2,4), (3,4), (1,2,3), (1,2,4), (1,3,4), (2,3,4), (1,2,3,4). More generally, we can say that for a sequence of size n, we can have (2n-1) non-empty sub-sequences in total.
Read full article from Subarray/Substring vs Subsequence and Programs to Generate them - GeeksforGeeks
A subbarray is a contiguous part of array. An array that is inside another array. For example, consider the array [1, 2, 3, 4], There are 10 non-empty sub-arrays. The subbarays are (1), (2), (3), (4), (1,2), (2,3), (3,4), (1,2,3), (2,3,4) and (1,2,3,4). In general, for an array/string of size n, there are n*(n+1)/2 non-empty subarrays/subsrings.
How to generate all subarrays?
We can run two nested loops, the outer loop picks starting element and inner loop considers all elements on right of the picked elements as ending element of subarray.
void subArray(int arr[], int n){ // Pick starting point for (int i=0; i <n; i++) { // Pick ending point for (int j=i; j<n; j++) { // Print subarray between current starting // and ending points for (int k=i; k<=j; k++) cout << arr[k] << " "; cout << endl; } }}A subsequence is a sequence that can be derived from another sequence by zero or more elements, without changing the order of the remaining elements.
For the same example, there are 15 sub-sequences. They are (1), (2), (3), (4), (1,2), (1,3),(1,4), (2,3), (2,4), (3,4), (1,2,3), (1,2,4), (1,3,4), (2,3,4), (1,2,3,4). More generally, we can say that for a sequence of size n, we can have (2n-1) non-empty sub-sequences in total.
void printSubsequences(int arr[], int n){ /* Number of subsequences is (2**n -1)*/ unsigned int opsize = pow(2, n); /* Run from counter 000..0 to 111..1*/ for (int counter = 1; counter < opsize; counter++) { for (int j = 0; j < n; j++) { /* Check if jth bit in the counter is set If set then print jth element from arr[] */ if (counter & (1<<j)) cout << arr[j] << " "; } cout << endl; }}