A fast Java solution, computing kth row directly!


  • 1
    B
    public List<Integer> getRow(int rowIndex) {
        List<Integer> result = new ArrayList<>();
        int half = rowIndex / 2; 
        long cur = 1;
        result.add((int)(cur));
        // since every row is symmetric, we just need to compute half of kth row
        for(int i = 1; i <= half; i++) {  
            cur = cur * (rowIndex - i + 1) / i;
            result.add((int)(cur));
        }
        if(rowIndex % 2 == 0) {
            half -= 1;
        }
        for(int i = half; i >= 0; i--) { 
            result.add(result.get(i));
        }
        return result;
    }
    

    In Pascal's Triangle, the value of ith integer in kth row is ( k! / ( i! * (k-i)! )). And you can learn more from wikipedia


Log in to reply
 

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