Java. Using combination to compute each coefficient mathematically. Just one more solution, not concise.


  • 0
    Z
    public class Solution {
        // computing coefficient of each element in  (x+y)^pow .
        public List<List<Integer>> generate(int numRows) {
            List<List<Integer>> ans = new ArrayList<>();
            int pow = numRows -1;
            for(int i =0; i <= pow; i ++){
                List<Integer> row = new ArrayList<>();
                for(int j =0; j <= i ; j ++)
                    row.add(comb(i, j));
                    
                ans.add(row);
            }
            
            return ans;
        }
        
        // select a balls from n identical balls
        int comb(int n, int a){
            if (a == 0)
                return 1;
                
            long ans = 1;
            for(int i = n -a +1, j =1; i <= n  ; i++, j ++){
                ans *= i;
                ans /= j;
            }
                
            return (int)ans;
        }
    }

Log in to reply
 

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