#include <stdio.h>
int main()
{
int a[100] = {0,1}; //初始化數組
int n, i, j;
int l, r; //存放上一層左邊的數和右邊的數
scanf("%d",&n); //層數
for(i = 1; i <= n; i++)
{
l = 0;
for(j = 1; j <= i ; j++)
{
r = a[j]; //面試題空白處
a[j] = l + r; //面試題空白處
printf("%-4d", a[j]);
l = r;
}
printf("\n");
}
}
滅有什麼需要解釋的;
最多,同一行中,左邊數字的前一行的右邊數字,正好是該數字的左邊數字 L=r
Int a[100]={0,1}前兩個元素爲 0,1;其他爲0;
認爲第一層的前一行元素爲 0,1
在此基礎上實現的HDUOJ2032題
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
int a[100] = {0,1}; //初始化數組
int n, i, j;
int l, r; //存放上一層左邊的數和右邊的數
while(~scanf("%d",&n)){ //層數
for(i = 1; i <= n; i++)
{
l = 0;
for(j = 1; j <= i ; j++)
{
r = a[j]; //面試題空白處
a[j] = l + r; //面試題空白處
printf("%d", a[j]);
l = r;
if(j!=i){
cout<<" ";
}
}
printf("\n");
}
a[0]=0;
a[1]=1;
for(i=2;i<100;i++){
a[i]=0;
}
cout<<endl;
}
}