#include <iostream>
#include <vector>
// Function to generate subarrays recursively
void subarr(const std::vector<int>& arr, int i, std::vector<int>& tmp) {
// base case
if (i == arr.size()) {
// If not empty, print the current subarray
if (!tmp.empty()) {// this is main case if null[] then skip
for (int j = 0; j < tmp.size(); j++) {
std::cout << tmp[j] << " ";
}
std::cout << std::endl;
}
return;
}
// Include the current element and move to the next element
tmp.push_back(arr[i]);
subarr(arr, i + 1, tmp);
// Exclude the current element and move to the next element
tmp.pop_back();
subarr(arr, i + 1, tmp);
}
// Function to initiate the subarray generation process
void sub(const std::vector<int>& arr) {
std::vector<int> tmp;
subarr(arr, 0, tmp);
}
int main() {
std::vector<int> arr = {1,2};
sub(arr);
return 0;
}
Execution and Stack Trace
Initial Call
sub(arr) initializes tmp as [] and calls subarr(arr, 0, tmp).
First Call to subarr(arr, 0, tmp)
i = 0, tmp = []
Includes arr[0] (which is 1): tmp = [1]
Calls subarr(arr, 1, tmp)
Second Call to subarr(arr, 1, tmp)
i = 1, tmp = [1]
Includes arr[1] (which is 2): tmp = [1, 2]
Calls subarr(arr, 2, tmp)
Third Call to subarr(arr, 2, tmp)
i = 2, tmp = [1, 2]
Base case reached: prints 1 2
Returns to second call
Back to Second Call
tmp = [1] (after tmp.pop_back())
Excludes arr[1]: tmp = [1]
Calls subarr(arr, 2, tmp)
Fourth Call to subarr(arr, 2, tmp)
i = 2, tmp = [1]
Base case reached: prints 1
Returns to first call
Back to First Call
tmp = [] (after tmp.pop_back())
Excludes arr[0]: tmp = []
Calls subarr(arr, 1, tmp)
Fifth Call to subarr(arr, 1, tmp)
i = 1, tmp = []
Includes arr[1] (which is 2): tmp = [2]
Calls subarr(arr, 2, tmp)
Sixth Call to subarr(arr, 2, tmp)
i = 2, tmp = [2]
Base case reached: prints 2
Returns to fifth call
Back to Fifth Call
tmp = [] (after tmp.pop_back())
Excludes arr[1]: tmp = []
Calls subarr(arr, 2, tmp)
Seventh Call to subarr(arr, 2, tmp)
i = 2, tmp = []
Base case reached: nothing to print
Returns to main function
Summary of Output
The function will print all non-empty subarrays of [1, 2]:
Copy code
1 2
1
2
Simplified Tracking Steps
Start with an empty subarray.
At each step, decide to either include or exclude the current element.
When reaching the end of the array, print the subarray if it is not empty.
Backtrack to explore other possibilities by excluding the last included element and moving to the next.
This explanation keeps the process straightforward by focusing on the decision at each step (include or exclude) and the resulting recursive calls.
To embed this project on your website, copy the following code and paste it into your website's HTML: