zoukankan      html  css  js  c++  java
  • [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;
        }



  • 相关阅读:
    hdu 6702 ^&^ 位运算
    hdu 6709 Fishing Master 贪心
    hdu 6704 K-th occurrence 二分 ST表 后缀数组 主席树
    hdu 1423 Greatest Common Increasing Subsequence 最长公共上升子序列 LCIS
    hdu 5909 Tree Cutting FWT
    luogu P1588 丢失的牛 宽搜
    luogu P1003 铺地毯
    luogu P1104 生日
    luogu P1094 纪念品分组
    luogu P1093 奖学金
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7365862.html
Copyright © 2011-2022 走看看