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

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

  • 相关阅读:
    移动页面HTML5自适应手机屏幕宽度
    “流式”前端构建工具——gulp.js 简介
    HDU2602-Bone Collector
    HDU3535-AreYouBusy
    HDU1712-ACboy needs your help
    HDU3496-Watch The Movie
    HDU1171-Big Event in HDU
    POJ2533-Longest Ordered Subsequence
    HDU2084-数塔
    HDU2023-求平均成绩
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/4733294.html
Copyright © 2011-2022 走看看