zoukankan      html  css  js  c++  java
  • 返回杨辉三角前 n 层的数字

    我的思路后来被证实是比较慢哈,思路很简单,递归地一行一行地往里插。是这样的:

    vector<vector<int>> generate(int numRows) {
        if (numRows < 1){
            return vector<vector<int>>();
        }
        
        if (numRows == 1){
            return vector<vector<int>>{vector<int>{1}};
        }
        
        auto&& lastLine = generate(numRows - 1);
        vector<int> thisLine;
        for (int i = 0; i != numRows - 1; ++i){
            if (i == 0){
                thisLine.push_back(1);
            }
            else{
                thisLine.push_back(lastLine[numRows - 2][i - 1]
                                   + lastLine[numRows - 2][i]);
            }
        }
        thisLine.push_back(1);
        lastLine.push_back(thisLine);
        return lastLine;
    }

    通过测试用了 4ms, 仍不是最好。出于习惯,我查看了投票数最高的方法,发现他的思路是迭代地填充:

    vector<vector<int> > generate(int numRows) {
        vector<vector<int>> r(numRows);
        
        for (int i = 0; i < numRows; i++) {
            // Set enough places.
            r[i].resize(i + 1);
            // Set the values of the edge.
            r[i][0] = r[i][i] = 1;
            
            // Evalue values in the middle.
            for (int j = 1; j < i; j++)
                r[i][j] = r[i - 1][j - 1] + r[i - 1][j];
        }
        
        return r;
    }

    注释是我加的,所以可能处于中国人看不懂,外国人看不明白的情况。希望谅解,领会精神哈。

  • 相关阅读:
    【洛谷P1119】灾后重建
    【洛谷P1462】通往奥格瑞玛的道路
    【洛谷P1991】无线通讯网
    poj 2892(二分+树状数组)
    hdu 1541(树状数组)
    hdu 5059(模拟)
    hdu 5056(尺取法思路题)
    poj 2100(尺取法)
    hdu 2739(尺取法)
    poj 3320(尺取法)
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4733294.html
Copyright © 2011-2022 走看看