Simple dp solution in java. O(k). pay attention to the diff between capacity and size of ArrayList


  • 0
    V
    public List<Integer> getRow(int rowIndex) {
        ArrayList<Integer> res = new ArrayList<Integer>(rowIndex + 1);//capacity set to rowIndex + 1;but the size of res is 0
        while (res.size() < rowIndex + 1) res.add(0);//now the size of res is rowIndex + 1
        
        res.set(0, 1);
        
        if (rowIndex == 0) return res;
        
        for (int i = 1; i < rowIndex + 1; i++) {
            for (int j = i; j > 0; j--) {
                res.set(j, res.get(j) + res.get(j - 1));
            }
        }
        
        return res;
    }

Log in to reply
 

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