leetcode 118. Pascal's Triangle
本帖最后由 Seawolf 于 2019-9-15 08:50 编辑Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.
In Pascal's triangle, each number is the sum of the two numbers directly above it.
Example:
Input: 5
Output:
[
,
,
,
,
]
import java.math.BigInteger;
class Solution {
public List<List<Integer>> generate(int numRows) {
List <List<Integer>> re = new ArrayList<>();
for(int i = 0; i< numRows; i++){
List <Integer> array = new ArrayList<>();
for(int j = 0; j<= i; j++){
int num = Integer.parseInt(mul(i-j+1,i).divide(mul(1,j)).toString());
array.add(num);
}
re.add(array);
}
return re;
}
public BigInteger mul(int start, int end){
BigInteger sum = BigInteger.ONE;
for(int i = start; i<= end; i++){
BigInteger num = new BigInteger(String.valueOf(i));
sum = sum.multiply(num);
}
return sum;
}
}
class Solution {
public List<List<Integer>> generate(int numRows) {
List <List<Integer>> re = new ArrayList<>();
if(numRows == 0) return re;
List <Integer> array = new ArrayList<>();
array.add(1);
re.add(array);
for(int i = 1; i < numRows; i++){
List<Integer> pre = re.get(i-1);
List<Integer> cur = new ArrayList<>();
cur.add(1);
for(int j = 1; j < i ; j++){
cur.add(pre.get(j) + pre.get(j-1));
}
cur.add(1);
re.add(cur);
}
return re;
}
}
页:
[1]