https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
[1],
[1,1],
[1,2,1],
[1,3,3,1],
[1,4,6,4,1]
]
Please review for performance.
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace RecurssionQuestions
{
/// <summary>
/// https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/601/
/// </summary>
[TestClass]
public class PascalTriangleTest
{
[TestMethod]
public void TestMethod1()
{
IList<IList<int>> result = PascalTriangle.Generate(5);
IList<IList<int>> expected = new List<IList<int>>();
expected.Add(new List<int> { 1 });
expected.Add(new List<int> { 1, 1 });
expected.Add(new List<int> { 1, 2, 1 });
expected.Add(new List<int> { 1, 3, 3, 1 });
expected.Add(new List<int> { 1, 4, 6, 4, 1 });
for (int i = 0; i < expected.Count; i++)
{
CollectionAssert.AreEqual(expected[i].ToList(), result[i].ToList());
}
}
}
public class PascalTriangle
{
public static IList<IList<int>> Generate(int numRows)
{
IList<IList<int>> result = new List<IList<int>>();
if (numRows == 0)
{
return result;
}
List<int> row = new List<int>();
row.Add(1);
result.Add(row);
if (numRows == 1)
{
return result;
}
for (int i = 1; i < numRows; i++)
{
var prevRow = result[i - 1];
row = new List<int>();
row.Add(1);
for (int j = 0; j < prevRow.Count - 1; j++)
{
row.Add(prevRow[j] + prevRow[j + 1]);
}
row.Add(1);
result.Add(row);
}
return result;
}
}
}