Mathematical solution :-)


  • 0
    C
    public class Solution {
        public List<Integer> getRow(int rowIndex) {
            List<Integer> result = new ArrayList<Integer>();
            int numElements = rowIndex + 1;
            for (int i = 0; i < numElements; i++) {
                double coeff = factorial(rowIndex) / (factorial(i) * factorial(rowIndex - i));
                result.add((int)Math.round(coeff));
            }
            return result;
        }
    
        public double factorial(int n) {
           if (n == 0) {
               return 1;
           } else {
               return n * factorial(n - 1);
           }
    
        }
    }

  • 0
    C
    Explanation:
    Zero based index.
    Given the rowIndex of the pascal triangle, you can determine each of the terms the row has with the following formula:
    rowIndex Choose termIndex.
    Example: rowIndex = 3, We know there are rowIndex + 1 terms: (1,3,3,1)
    The first term (1) can be determined by 3 choose 0
    The second term (3) can be determined by 3 choose 1
    The third term (3) can be determined by 3 choose 2
    The forth term (1) can be determined by 3 choose 3.

  • 0
    B

    This is the first solution come to my mind when i saw the problem. However, factorial is an expensive computation, it reduces performance greatly if you compare to other O(k) solution.


Log in to reply
 

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