点击查看:蓝桥杯历年真题 题解目录
杨辉三角
1.本题的得出结果的方式为逐行迭代的方式
2.本题将元素存放在一维数组中, "在二维数组中,每个元素都需要上一行的元素+写上放的元素"
3.采用一行更新的方式,即新行的元素需要从后向前循环迭代
4.从后向前迭代,才能保证前一个元素是上行的元素。
参考答案:
int q=p-1;q>=1; q--
正确直接得分,否则把用户答案带入测评代码中的######,运行结果比对:
15
20
137846528820
public class Main005_杨辉三角{
// 杨辉三角形的第row行第col列
static long f(int row, int col){
if(row<2) return 1;
if(col==0) return 1;
if(col==row) return 1;
long[] a = new long[row+1];
a[0]=1;
a[1]=1;
int p = 2;
while(p<=row){
a[p] = 1;
for(int q=p-1;q>=1;q-- )
a[q] = a[q] + a[q-1];
p++;
}
return a[col];
}
public static void main(String[] args){
System.out.println(f(6,2));
System.out.println(f(6,3));
System.out.println(f(40,20));
}
}