简体   繁体   中英

Print all subarrays in less than O(n^3) time complexity

To print all the subarrays (contiguous subsequences) of a given array, one requires three nested for loops. Is there a way to reduce the time complexity of O(n^3) using map in C++ STL?

#include<bits/stdc++.h>
using namespace std;
int main()
{
ios_base::sync_with_stdio (false);
cin.tie(NULL);
cout.tie(NULL);
vector<int> v;
int n;
cin>>n;   // the size of the array
for(int i=0;i<n;i++)
{
int x;
cin>>x;
v.push_back(x);
}
for(int i=0;i<n;i++)
{
for(int j=i;j<n;j++)
{
for(int k=i;k<=j;k++)
cout<<v[k]<<" ";
cout<<endl;
}
}
return 0;
}

If you must iterate all elements then you must iterate all elements... No further reduction possible. Reducing time complexity is all about finding ways in which you don't need to iterate all elements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM