华为机试题 蛇形数组

简介

找规律, 而不是盲目转弯, 这样太慢.

code

参考了题解

#include <iostream>
#include <vector>

using namespace std;
int a[101][101]={0};
int main() {
    int n;
    vector<int> b;
    while(cin >> n) {
        int i=0;
        int dis = 2;
        for(int j=0; j<n-i; j++){
            if(i ==0 && j==0) a[i][j] = 1;
            else{
                a[i][j] = a[i][j-1] + dis;
                dis += 1;
                b.push_back(a[i][j]);
            }
        }
        for(int i=1; i<n; i++) {
            vector<int> c;
            for(int j=0; j<n-i; j++){
                if(j==0){
                    a[i][j] = b[j] - 1;
                }else{
                    a[i][j] = b[j] - 1;
                    c.push_back(a[i][j]);
                }
            }
            b.assign(c.begin(), c.end());
        }
        for(int i=0; i<n; i++){
            for(int j=0; j<n-i; j++){
                if(j == 0) cout << a[i][j];
                else cout << " " << a[i][j];
            }
            cout << "
";
        }
    }
    
}
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14941003.html