杨辉三角的解法
二维数组的解法:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3;
typedef long long ll;
using namespace std;
int main(){
ios::sync_with_stdio(false);
int a[100][100] = {0};
int n;
cin >> n;
a[1][1] = 1;
for(int i = 2;i<=n;i++){
for(int j = 1;j<=i;j++){
a[i][j] = a[i-1][j] + a[i-1][j-1];
}
}
for(int i = 1;i<=n;i++){
for(int j = 1;j<=i;j++){
cout << a[i][j] << ' ';
}
cout << endl;
}
return 0;
}
组合数的解法:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3;
typedef long long ll;
using namespace std;
int Cc(int a,int b){
ll res=1;
for(int i=1;i<=b;i++){
res = res*(a-b+i)/i;
}
return res;
}
int main(){
ios::sync_with_stdio(false);
int n;
cin >> n;
cout << '1' << endl;
for(int i = 1;i<n;i++){
for(int j = 0;j<=i;j++){
cout << Cc(i,j) << ' ';
}
cout << endl;
}
return 0;
}
一维数组解法:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3;
typedef long long ll;
using namespace std;
int main(){
ios::sync_with_stdio(false);
int n;
cin >> n;
ll a[520] = {0,1};
int l,r;
for(int i = 1;i<=n;i++){
l = 0;
for(int j = 1;j<=i;j++){
r = a[j];
a[j] = l+r;
l = r;
cout << a[j] << ' ';
}
cout << endl;
}
return 0;
}