Skip to content

Latest commit

 

History

History
29 lines (25 loc) · 868 Bytes

Pascal's_TriangleII.md

File metadata and controls

29 lines (25 loc) · 868 Bytes

Pascal's Triangle II

Given an index k, return the kth row of the Pascal's triangle.


public class Solution {  
    public List getRow(int rowIndex) {  
        List list = new ArrayList();
        
        list.add(1);
        List prev = new ArrayList(list);
        for (int i = 1; i <= rowIndex; i++) {
            list.clear();
            list.add(1);
            for (int j = 1; j < i; j++) {
                list.add(prev.get(j) + prev.get(j - 1));
            }
            list.add(1);
            prev.clear();
            prev.addAll(list);
        }
        return list;
    }  
}  

  • 维护prev数组,该数组中存储上一行的元素。
  • list数组中一直存储当前行元素。
  • 两层循环,外层循环遍历所有行,内层循环遍历需要添加的元素。