【leetcode】118.(Easy)Pascal's Triangle

解题思路:
递归
时间复杂度:O(n) n是最终所有元素的个数和

提交代码:

class Solution {
    public List<List<Integer>> generate(int numRows) {
        List<List<Integer>> res=new ArrayList<List<Integer>>();
        if(numRows==0)	return res;
        List<Integer> curRow=new ArrayList<Integer>();
        curRow.add(1);
        res.add(curRow);
        addRow(numRows-1,curRow,res);
        return res;
    }
    
    private void addRow(int numRows,List<Integer> parentRow,List<List<Integer>>res) {
    	if(numRows==0)	return;
    	List<Integer> curRow=new ArrayList<>();
    	curRow.add(1);
    	for(int i=1;i<parentRow.size();i++) 
    		curRow.add(parentRow.get(i-1)+parentRow.get(i));
    	curRow.add(1);
    	res.add(curRow);
    	addRow(numRows-1,curRow,res);
    }
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/AXIMI/article/details/85451623