leetcode118

public class Solution {
    public IList<IList<int>> Generate(int numRows) {
        var list = new List<IList<int>>();

            for (int i = 0; i < numRows; i++)
            {
                var row = new List<int>();
                if (i == 0)
                {
                    row.Add(1);
                }
                else if (i == 1)
                {
                    row.Add(1);
                    row.Add(1);
                }
                else
                {
                    var prerow = list[i - 1].ToList();

                    for (int j = 0; j <= i; j++)
                    {
                        if (j == 0)
                        {
                            row.Add(1);
                        }
                        else if (j == i)
                        {
                            row.Add(1);
                        }
                        else
                        {
                            row.Add(prerow[j - 1] + prerow[j]);
                        }
                    }
                }
                list.Add(row);
            }

            return list;
    }
}

https://leetcode.com/problems/pascals-triangle/#/description

时间: 2024-11-06 13:10:45

leetcode118的相关文章

LeetCode118 Pascal&#39;s Triangle

Given numRows, generate the first numRows of Pascal's triangle. For example, given numRows = 5, (Easy)Return [ [1], [1,1], [1,2,1], [1,3,3,1], [1,4,6,4,1] ] 分析: 求解杨辉三角形,按照其定义以此求解即可,注意优化写法使其能够更简洁(比如对于二维数组每一行的个数其实是已知的,所以可以先push_back一个长度的数组,后面直接用下标访问),即

LeetCode118——Pascal&#39;s Triangle

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] ] 题目大意 给定numRows,生成帕斯卡三角的前numRows行. 难度系数:容易 实现 vector<vector<int> > generate(int rowIndex) { v

每天一道LeetCode--118. Pascal&#39;s Triangle(杨辉三角)

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] ] solution: ackage cn.magicdu; import java.util.ArrayList; import java.util.List; public class _118_Pa

LeetCode118:Pascal&amp;#39;s Triangle

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] ] Subscribe to see which companies asked this question //解题思路:利用一个中间vector来保存每层的数 class Solution { pu

2017-3-6 leetcode 118 169 189

今天什么都没发生 ================================================= leetcode118 https://leetcode.com/problems/pascals-triangle/?tab=Description leetcode169 https://leetcode.com/problems/majority-element/?tab=Description leetcode189 https://leetcode.com/proble