This is LeetCode question 118 Pascal's triangle.
Given an integer numRows, return the first numRows of Pascal's triangle.
There is an example.
Input: numRows = 5
Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
I am interested to know the time complexity of my solution, and how I can further improve it. I am thinking that the time complexity is O(mn) with n being numRows
and m being the size of each row when calling my AddToTriangle
function. Is there a way to condense this to a single loop and not a loop and another loop in a different function call? This is written in c#.
public IList<IList<int>> Generate(int numRows) {
IList<IList<int>> triangle = new List<IList<int>>();
for (int i = 1; i <= numRows; i++){
if (i > 2)
AddToTriangle(triangle);
else if (i == 2)
triangle.Add(new List<int> { 1, 1 });
else
triangle.Add(new List<int> { 1 });
}
return triangle;
}
private void AddToTriangle(IList<IList<int>> triangle){//passing in triangle by reference
IList<int> row = triangle[triangle.Count - 1];//getting the last row in the List
triangle.Add(new List<int> { 1 });//creating a new row to append to
int index = triangle.Count - 1;//getting the last row to append to it
for (int i = 0; i < row.Count; i++){
int value = 1;
if (i + 1 < row.Count)
value = row[i] + row[i + 1];
triangle[index].Add(value);
}
}