Given two integers r and c, return the value at the rth row and cth column (1-indexed) in a Pascal's Triangle.
int nCr(int n, int r) { //ncr of row-1Ccol-1 gives value at exact position
if (r > n - r) r = n - r;
if (r == 1) return n;
int res = 1;
for (int i = 0; i < r; i++) {
res = res * (n - i);
res = res / (i + 1);
}
return res;
}
int pascalTriangleI(int r, int c) {
return nCr(r - 1, c - 1);
}
Given an integer r, return all the values in the rth row (1-indexed) in Pascal's Triangle in correct order.
vector<int> pascalTriangleII(int r)
{
vector<int> ans(r);
ans[0] = 1;
for (int i = 1; i < r; i++)
{
ans[i] = ans[i - 1] * (r - i) / i; //curr = (prev * (r-i))/(i)
}
return ans;
}
Given an integer n, return the first n (1-Indexed) rows of Pascal's triangle.
class Solution {
private:
vector<int> generateRow(int r){
vector<int> ans(r);
ans[0] = 1;
for (int i = 1; i < r; i++)
{
ans[i] = ans[i - 1] * (r - i) / i;
}
return ans;
}
public:
vector<vector<int>> pascalTriangleIII(int n) {
vector<vector<int>> ans;
for(int i=1;i<=n;i++) ans.push_back(generateRow(i));
return ans;
}
};