题意:
方法一:
找规律
思路:
![]()
#include <bits/stdc++.h>
using namespace std;
int main(){
int m;
while(cin >> m){
int x=(m-1)*m/2+1;//m个连续奇数中第一个奇数的序号
string res="";
res+=to_string(2*x-1);//遍历第一个奇数
x++;
for(int i=1;i<m;i++){//遍历剩下的奇数
res+='+';
res+=to_string(2*x-1);
x++;
}
cout << res << endl;
}
return 0;
}
时间复杂度:
空间复杂度:![]()
方法二:
暴力模拟
思路:先遍历前m-1行的所有奇数,最后遍历第m行的m个奇数。最后,直接输出。
#include <bits/stdc++.h>
using namespace std;
int main(){
int m;
while(cin >> m){
string res="";
int x=-1;
for(int i=1;i<m;i++){//遍历前m-1行
for(int j=0;j<i;j++){
x+=2;
}
}
x+=2;//第m行的第一个奇数
res+=to_string(x);
x+=2;
for(int i=1;i<m;i++){//第m行的其余奇数
res+='+';
res+=to_string(x);
x+=2;
}
cout << res << endl;
}
return 0;
}
时间复杂度:
空间复杂度:![]()



京公网安备 11010502036488号