您现在的位置是:首页 > 后台技术 > 数据结构与算法数据结构与算法
杨辉三角 II(图文)
第十三双眼睛2023-11-28【数据结构与算法】人已围观
简介杨辉三角 II
给定一个非负索引 rowIndex,返回「杨辉三角」的第 rowIndex 行。
在「杨辉三角」中,每个数是它左上方和右上方的数的和。
思路:之前的是返回整个数组,现在是返回指定的一行,其实更容易了,如果是第一行或者第二行,直接写好两个数组返回,如果是3行以上,则需要用上一行的元素进行构建。代码如下:
public static List<Integer> method2(int num) { if (num == 0) { List<Integer> res = new ArrayList<>(); res.add(1); return res; } if (num == 1) { List<Integer> res = new ArrayList<>(); res.add(1); res.add(1); return res; } List<Integer> tempList = new ArrayList<>(); List<Integer> resList = new ArrayList<>(); tempList.add(1); tempList.add(1); int temp = 2; while (temp <= num) { resList.add(1); for (int i = 1; i < temp; i ++) { resList.add(tempList.get(i - 1) + tempList.get(i)); } resList.add(1); tempList.clear(); tempList.addAll(resList); resList.clear(); temp ++; } return tempList; } |
Tags:
很赞哦! ()
上一篇:杨辉三角(图文)
下一篇:买卖股票的最佳时机(图文)