java版杨辉三角

	public List<List<Integer>> generate(int numRows){
		List<List<Integer>> triangle = new ArrayList<List<Integer>>();
		
		if(numRows == 0) {
			return triangle;
		}
		
		triangle.add(new ArrayList<>());
		triangle.get(0).add(1);
		
		for(int rowNum = 1; rowNum < numRows; rowNum++) {
			List<Integer> row = new ArrayList<>();
			List<Integer> 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;
	}

猜你喜欢

转载自blog.csdn.net/perception952/article/details/83479309