热线电话:13121318867

登录
2019-01-18 阅读量: 688
如何使用递归生成子数组

给定一个数组,使用递归生成给定数组的所有可能的子数组。

例子:

方法:我们使用两个指针startend来维护数组的起点和终点,并按照下面给出的步骤操作:

  • 如果我们到达数组的末尾就停止
  • 如果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;

}

109.0909
3
关注作者
收藏
评论(0)

发表评论

暂无数据
推荐帖子