博主并没有什么算法基础,所以写的不好,勿喷,抛砖引玉,欢迎交流,感谢。
//给定一个非负整数 numRows,生成杨辉三角的前 numRows 行。
// 在杨辉三角中,每个数是它左上方和右上方的数的和。
// 示例:
// 输入: 5
//输出:
//[
// [1],
// [1,1],
// [1,2,1],
// [1,3,3,1],
// [1,4,6,4,1]
//]
// Related Topics 数组
// 👍 349 👎 0
package com.zqh.leetcode.editor.cn;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
//Java:杨辉三角
public class P118PascalsTriangle {
public static void main(String[] args) {
Solution solution = new P118PascalsTriangle().new Solution();
System.out.println(solution.generate(5));
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<Integer>> generate(int numRows) {
List<List<Integer>> result = new ArrayList<>(numRows);
if (0 == numRows) {
return result;
}
List<Integer> array = Arrays.asList(1);
result.add(array);
if (1 == numRows) {
return result;
}
triangle(result, array, numRows, 2);
return result;
}
/**
* @param result 结果集
* @param upperArray 上一层的结果
* @param totalNumRows 总行数
* @param currentNumRows 当前行数
*/
public void triangle(List<List<Integer>> result, List<Integer> upperArray, int totalNumRows, int currentNumRows) {
List<Integer> currentArray = new ArrayList<>(currentNumRows);
for (int i = 0; i < currentNumRows; i++) {
if (i == 0 || i == currentNumRows - 1) {
// 如果是首位或末尾,就直接设置1
currentArray.add(1);
continue;
}
// 其他的就拿取上一层结果的前一坐标值+当前坐标值
currentArray.add(upperArray.get(i - 1) + upperArray.get(i));
}
result.add(currentArray);
if (totalNumRows != currentNumRows) {
// 还没到指定行数,就继续循环
triangle(result, currentArray, totalNumRows, ++currentNumRows);
}
}
}
//leetcode submit region end(Prohibit modification and deletion)
}