给定一个数组,使用递归生成给定数组的所有可能的子数组。
例子:
方法:我们使用两个指针start和end来维护数组的起点和终点,并按照下面给出的步骤操作:
- 如果我们到达数组的末尾就停止
- 如果start大于end,则递增结束索引
- 从索引开始到结束打印子数组并增加起始索引
以下是上述方法的实现。
// C++ code to print all possible subarrays
// for given array using recursion
#include <iostream>
# include <vector>
using namespace std;
// Recursive function to print all possible subarrays
// for given array
void printSubArrays(vector<int> arr, int start, int end)
{
// Stop if we have reached the end of the array
if (end == arr.size())
return;
// Increment the end point and start from 0
else if (start > end)
printSubArrays(arr, 0, end + 1);
// Print the subarray and increment the starting point
else
{
cout << "[";
for (int i = start; i < end; i++){
cout << arr[i] << ", ";
}
cout << arr[end] << "]" << endl;
printSubArrays(arr, start + 1, end);
}
return;
}
int main()
{
vector<int> arr = {1, 2, 3};
printSubArrays(arr, 0, 0);
return 0;
}








暂无数据