⏰ Time complexity: O(n^2). generate is called for numRows times, and in that we have loop to fill newRow from old row, and that takes O(n) time. So, time complexity is O(n^2).
classSolution {
public List < List<Integer>>generate(int numRows) {
List < List<Integer>> ans =new ArrayList<>();
for (int row = 1; row <= numRows; row++) {
List<Integer> currRow =new ArrayList<>();
for (int col = 1; col <= row; col++) {
currRow.add(binomialCoeff(row - 1, col - 1));
}
ans.add(currRow);
}
return ans;
}
privateintbinomialCoeff(int n, int k) {
int ans = 1;
if (k > n - k) {
k = n - k;
}
for (int i = 0; i < k; ++i) {
ans *= (n - i);
ans /= (i + 1);
}
return ans;
}
}
classSolution {
public List < List<Integer>>generate(int numRows) {
List <List<Integer>> ans =new ArrayList<>();
// do the first row separately to avoid if condition on prevRow in loop List<Integer> firstRow =new ArrayList<>();
firstRow.add(1);
ans.add(firstRow);
// note: no row<= numRows, as first row already handledfor (int row = 1; row < numRows; row++) {
List<Integer> prevRow = ans.get(row - 1);
List<Integer> currRow =new ArrayList<>();
currRow.add(1);
// no col <= row here as well, to handle index out of boundsfor (int col = 1; col < row; col++) {
currRow.add(prevRow.get(col - 1) + prevRow.get(col));
}
currRow.add(1);
ans.add(currRow);
}
return ans;
}
}