• 【Pascal's Triangle】cpp


    题目:

    Given numRows, generate the first numRows of Pascal's triangle.

    For example, given numRows = 5,
    Return

    [
         [1],
        [1,1],
       [1,2,1],
      [1,3,3,1],
     [1,4,6,4,1]
    ]

    代码:

    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
                vector<vector<int> > ret;
                if ( numRows<1 ) return ret;
                vector<int> pre, curr;
                for ( int i=0; i<numRows; ++i )
                {
                    curr.clear();
                    curr.push_back(1);
                    for ( int j=0; j<pre.size(); ++j )
                    {    
                        if ( j==pre.size()-1 ){
                            curr.push_back(1);
                        }
                        else{
                            curr.push_back(pre[j]+pre[j+1]);
                        }
                    }
                    pre = curr;
                    ret.push_back(curr);
                }
                return ret;
        }
    };

    tips:

    数组基本操作。

    ==============================================

    第二次过这道题,代码更简洁了。

    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
                vector<vector<int> > ret;
                if ( numRows<1 ) return ret;
                vector<int> pre;
                pre.push_back(1);
                ret.push_back(pre);
                for ( int i=1; i<numRows; ++i )
                {
                    pre = ret.back();
                    vector<int> curr;
                    curr.push_back(1);
                    for ( int j=1; j<pre.size(); ++j ) curr.push_back(pre[j-1]+pre[j]);
                    curr.push_back(1);
                    ret.push_back(curr);
                }
                return ret;
        }
    };

    ===========================================

    第三版,更简洁了一些

    class Solution {
    public:
        vector<vector<int>> generate(int numRows) {
            vector<vector<int> > ret;
            if (numRows==0) return ret;
            vector<int> tmp;
            tmp.push_back(1);
            ret.push_back(tmp);
            for ( int i=1; i<numRows; ++i )
            {
                for ( int j=tmp.size(); j>0; --j ) tmp[j] = tmp[j] + tmp[j-1];
                tmp.push_back(1);
                ret.push_back(tmp);
            }
            return ret;
        }
    };
  • 相关阅读:
    FFMPEG 中dts和pts区别
    time_base
    [总结]FFMPEG视音频编解码零基础学习方法
    autolayout收集,适配,自动布局 状态栏 applicationFrame
    滑出式导航面板
    WPF与WCF c#
    App Icons on iPad and iPhone UI 尺寸
    mac iPhone管理工具
    scrollview背景
    网络编程链接
  • 原文地址:https://www.cnblogs.com/xbf9xbf/p/4562242.html
Copyright © 2020-2023  润新知