题解 | #尼科彻斯定理#

尼科彻斯定理

http://www.nowcoder.com/practice/dbace3a5b3c4480e86ee3277f3fe1e85

题意:



方法一:
找规律


思路:
       
            
           



#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;
}

时间复杂度:
空间复杂度:





全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务