【问题标题】:How to print all the contiguous subarray of the array如何打印数组的所有连续子数组
【发布时间】:2017-12-01 05:33:33
【问题描述】:

我正在研究一些算法,我想找到数组的连续子数组。

例如,如果我的输入数组如下,

vector<int> nums = {1, 2, 2, 3, 1}

我想得到如下的输出向量,

vector<vector<int>> output;
//Output should contain {1, 2, 2, 3, 1}, {1, 2, 2, 3}, {2, 2, 3, 1}, 
//{1, 2, 2}, {2, 2, 3}, {2, 3, 1},{1, 2}, {2, 2}, 
//{2, 3}, {3, 1}, {1}, {2}, {2}, {3}, {1} 

【问题讨论】:

  • 按 w.r.t 的顺序生成所有可能的索引对。长度。
  • 这肯定会解决问题,但我正在寻找相同的算法。

标签: c++ algorithm vector stl


【解决方案1】:

我刚刚想通了算法,如下图,

vector<vector<int>> Solution::sliceArray(vector<int> vect)
{
  vector< vector<int> > listOfVect;
  for (size_t i = 0; i < vect.size(); i++)
  {
    for (size_t j = 0; j <= i; j++)
    {
      vector<int>  indVect(vect.size() -i );
      copy(vect.begin() + j , vect.end() - i + j , indVect.begin());
      listOfVect.push_back(indVect);
    }
  }
  return listOfVect;
}

【讨论】:

    猜你喜欢
    • 2020-06-24
    • 2021-06-05
    • 2020-09-18
    • 1970-01-01
    • 2020-12-02
    • 2017-05-25
    • 2015-12-08
    • 1970-01-01
    • 2016-09-02
    相关资源
    最近更新 更多