public class Solution {
public IList<IList<int>> Generate(int numRows) {
List<List<int>>res = new List<List<int>>();
res.Add(new List<int>(){1}); //the first line
if(numRows!=1)
{
for(int i = 1;i<numRows;i++)
{
List<int>tmp = new List<int>(); //temp array
for(int j=0;j<=i;j++)
{
int num;
if(j==0 || j==i) //the first and end number of a line is one
{
num = 1;
}
else
{
num = res[i-1][j-1]+res[i-1][j];
}
tmp.Add(num);
}
res.Add(tmp); //add temp array to the result
}
}
return res.ToArray();
}
}
Java Solution
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>>res = new ArrayList<List<Integer>>();
res.add(Arrays.asList(new Integer[]{1}));
if(numRows!=1)
{
for(int i = 1;i<numRows;i++)
{
List<Integer>tmp = new ArrayList<Integer>();
for(int j=0;j<=i;j++)
{
int num;
if(j==0 || j==i)
{
num = 1;
}
else
{
num = res.get(i-1).get(j-1)+res.get(i-1).get(j);
}
tmp.add(num);
}
res.add(tmp);
}
}
return res;
}
}
Runtime : 1ms
Python3 Solution
class Solution:
def generate(self, numRows: int) -> List[List[int]]:
res = [];
res.append([1]);
if numRows!=1:
for i in range(1,numRows):
tmp = [];
for j in range(0,i+1):
if j==0 or j==i :
tmp.append(1);
else:
tmp.append(res[i-1][j-1]+res[i-1][j]);
res.append(tmp);
return res;
JavaScript Solution
Solution1
/**
* @param {number} numRows
* @return {number[][]}
*/
var generate = function(numRows) {
var res = [];
res[0] = [1];
if(numRows!=1)
{
for(let i = 1;i<numRows;i++)
{
let tmp = [];
for(let j=0;j<=i;j++)
{
var num;
if(j==0 || j==i)
{
num = 1;
}
else
{
num = res[i-1][j-1]+res[i-1][j];
}
tmp[j] = num;
}
res[i] = tmp;
}
}
return res;
};
Conclusion
🧡If my solution helps, that is my honor!
🧡You can support me by clicking some ad, Thanks a lot !
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};