My 0ms accepted Java solution using a property of nCr.


  • 1
    X

    High level description:
    We know that each element of Pascal's triangle is just nCr, where n is the row number and r is the column number.
    Now, if we know the value of nCr, then we can calculate the value of nCr+1 (i.e. for the next column).
    If you expand nCr+1, it can be written as: nCr * (n-r)/(r+1).
    Thus, I make a for loop which runs k time and calculates nCr+1 by using nCr.
    Here is the code. Feel free to ask questions and make suggestions.

    Code:

    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            long coeff = 1; // nC0
            // n = rowIndex, j=r
            List<Integer> result = new ArrayList<Integer>();
            for(int j=0;j<=rowIndex;j++){
                    result.add((int)coeff);
                    coeff = coeff * (rowIndex-j)/(j+1); // calculating nCr using nCr-1
                }
            return result;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.