java版杨辉三角

	public List> generate(int numRows){
		List> triangle = new ArrayList>();
		
		if(numRows == 0) {
			return triangle;
		}
		
		triangle.add(new ArrayList<>());
		triangle.get(0).add(1);
		
		for(int rowNum = 1; rowNum < numRows; rowNum++) {
			List row = new ArrayList<>();
			List preRow = triangle.get(rowNum-1);
			
			//The first row element is always 1.
			row.add(1);
			
			//Each triangle element (other than the first and last of eachrow)
			//is equal to the sum of the elements obve-and-to-the-left and 
			//obve-and-to-the-right
			for(int j = 1; j < rowNum; j++) {
				row.add(preRow.get(j-1) + preRow.get(j));
			}
			
			row.add(1);
			
			triangle.add(row);
			
		}
		
		return triangle;
	}

 

你可能感兴趣的:(每日一题)