Given an index k, return the kth row of the Pascal’s triangle.
For example, given k = 3,
Return [1,3,3,1].
Note:
Could you optimize your algorithm to use only O(k) extra space?
Method 1: (Pascal’s rule)
public class Solution {
public List<Integer> getRow(int numRows) {
Integer[] rowArray = {};
for(int i = 0; i < numRows+1; i++){
Integer[] tempArray = new Integer[i+1];
tempArray[0] = 1;
tempArray[tempArray.length - 1] = 1;
for(int j = 1; j < i; j++){
tempArray[j] = rowArray[j-1] + rowArray[j];
}
rowArray = tempArray;
}
return Arrays.asList(rowArray);
}
}
Method 2:(Get the element by using the combination number)
public class Solution {
public List<Integer> getRow(int numRows) {
Integer[] arr = new Integer[numRows+1];
for (int i = 0; i < arr.length; i++) {
if(i == 0 || i == arr.length - 1){
arr[i] = 1;
continue;
}
Long d = Math.round(multi(numRows)/(multi(numRows-i)*multi(i)));
arr[i] = d.intValue();
}
return Arrays.asList(arr);
}
public double multi(int m){
double sum = 1;
while(m > 0){
sum = sum * m;
m--;
}
return sum;
}
}