打印杨辉三角形
打印杨辉三角形
杨辉三角形就是呈现金字塔型的结构 每个的数字表达式为:a(n,x) = a(n - 1,x) + a(n - 1,x - 1)
结构如下:
1
1,1
1,2,1
1,3,3,1
1,4,6,4,1
解题思路:
循环打印的行数,由于对称型每行的数据类型可以只计算一半,后面的一半完全对折过来。
上代码:
public static List<List<Integer>> yangTrig(int num){
if (num <= 0) {
return null;
}
List<List<Integer>> result = new ArrayList<>();
for (int i = 0; i < num; i++) {
//填充数组列表list,否则后面set会报索引越界异常
List<Integer> list = new ArrayList<Integer>(Collections.nCopies(i+1, 0));
list.set(0, 1);
list.set(i, 1);
int length = (i+1) % 2 == 0 ? (i+1) / 2 - 1 : (i+1) / 2;
for (int j = 1; j <= length; j++) {
int temp = result.get(i - 1).get(j) + result.get(i - 1).get(j - 1);
list.set(j, temp);
list.set(i - j, temp);
}
result.add(list);
}
return result;
}
复杂度的计算:
由于两次循环,过程没有额外的存储空间,所以时间复杂度和空间复杂度为:
时 间 复 杂 度 = O ( n 2 ) 空 间 复 杂 度 = O ( 1 ) 时间复杂度=O(n^2) 空间复杂度=O(1) 时间复杂度=O(n2)空间复杂度=O(1)