Problem: Given an integer numRows, return the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it as shown:
Example:
Input: numRows = 5 Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
Input: numRows = 1 Output: [[1]]
Approach: It's just simple implementation problem. Please have a look at implementation directly.
Implementation in C#:
public IList<IList<int>> Generate(int numRows)
{
var result = new List<IList<int>>();
if (numRows == 0)
{
return result;
}
result.Add(new List<int> {1});
if (numRows == 1)
{
return result;
}
result.Add(new List<int> {1, 1});
for (int i = 2; i < numRows; ++i)
{
var currRow = new List<int>();
var lastRow = result[i - 1];
currRow.Add(1);
for (int j = 1; j < i; ++j)
{
currRow.Add(lastRow[j - 1] + lastRow[j]);
}
currRow.Add(1);
result.Add(currRow);
}
return result;
}
Complexity: O(n^2)
No comments:
Post a Comment