• [leetcode]118,119PascalsTriangle,杨辉三角1,2


    杨辉三角1
    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]
    ]
    构建杨辉三角,从第一行开始构建,比较简单
    public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> res = new ArrayList<>();
            if (numRows < 1)
                return res;
            List<Integer> one = new ArrayList<>();
            one.add(1);
            res.add(one);
            for (int i = 1; i < numRows; i++) {
                List<Integer> cur = new ArrayList<>();
                cur.add(1);
                int num = 1;
                while (num < i)
                {
                    cur.add(res.get(i-1).get(num)+res.get(i-1).get(num-1));
                    num++;
                }
                cur.add(1);
                res.add(cur);
            }
            return res;
        }


    杨辉三角2
    Given an index k, return the kth row of the Pascal's triangle.

    For example, given k = 3,
    Return [1,3,3,1].

    Note:
    Could you optimize your algorithm to use only O(k) extra space?
    要求直接输出第K行
    由于有空间限制,只能在本地进行构建杨辉三角,内循环用来更新数据,外循环用来记录第几行

    public  List<Integer> getRow(int rowIndex) {
            List<Integer> res = new ArrayList<>();
            if(rowIndex<0)
                return res;
            //第一行
            res.add(1);
            for(int i=1;i<=rowIndex;i++)
            {
                //从后边开始向前更新数据,第一个数不更新
                for(int j=res.size()-2;j>=0;j--)
                {
                    //当前的数加上前边的数就是下一行的当前位置数
                    res.set(j+1,res.get(j)+res.get(j+1));
                }
                //循环完后加上最后的1就是更新好了一行
                res.add(1);
            }
            return res;
        }



  • 相关阅读:
    uvalive 3971 Assemble
    poj 1064 Cable master
    1130mysql explain中的type列含义和extra列的含义
    1128ORDER BY的原理
    1125Sending data
    1125MySQL Sending data导致查询很慢的问题详细分析
    1125mysqbinlog日志
    1122Shell脚本之利用mysqldump备份MySQL数据库
    1122从业务优化MYSQL
    1122MySQL性能优化之 Nested Loop Join和Block Nested-Loop Join(BNL)
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7365862.html
Copyright © 2020-2023  润新知