Java Call Binomial Function 1ms 40%


  • 0
    J

    public class Solution {

    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> result = new ArrayList<>(numRows);
        List<Integer> list;
        
        for(int n=0; n<numRows; n++){
            list = new ArrayList<Integer>(n+1);
            for(int k=0; k<=n; k++){
                if(k==0||k==n){
                    list.add(1);
                }else{
                    list.add(binomial(k,n));
                }
            }
            result.add(list);
        }
        
        return result;
    }
    
    public int binomial(int k, int n){
        if (k > n/2) {
            k = n - k;
        }
    
        double denominator = 1.0, numerator = 1.0;
        for (int i = 1; i <= k; i++) {
            denominator *= i;
            numerator *= (n + 1 - i);
        }
        return (int)(numerator / denominator);
    }
    

    }


Log in to reply
 

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