1.杨辉三角
算法思想:
a[i][j]=a[i-1][j]+a[i-1][j-1];
代码:
#include<iostream>
using namespace std;
const int N = 1e2 + 10;
int a[N][N];
int main() {int n; cin >> n;a[1][1] = a[2][1] = a[2][2] = 1;for (int i = 3; i <= n; i++) {for (int j = 1; j <= i; j++) {if (j == 1 || j == i) a[i][j] = 1;else 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;
}
2.蛇形添数
算法思想:下左上右,自己多模拟几遍
#include <iostream>
#include <algorithm>
const int N=1e4+10;
int nums[N][N],n,l,r,x;
using namespace std;
void text01(){cin>>n;//4l=1;r=n;while(x<n*n){//x<16for(int i=l;i<=r;i++){//下nums[i][r]=++x;}for(int j=r-1;j>=l;j--){//左nums[r][j]=++x;}for(int i=r-1;i>=l;i--){//上nums[i][l]=++x;}for(int j=l+1;j<=r-1;j++){//右nums[l][j]=++x;}l++;r--;}for(int i=1;i<=n;i++){for(int j=1;j<=n;j++){cout<<nums[i][j]<<" ";}cout<<endl;}
}int main() {text01();return 0;
}
3.矩阵乘法
核心算法
A n m
B m k
最里层循环,假设是A的第一行*B的第一列,恰好遍历长度都是m所以最里层是m的循环
次里层循环,是k的循环
最外层循环,是n的循环
#include<iostream>
using namespace std;
const int N = 1e2 + 10;
int a[N][N],b[N][N],c[N][N];
int main() {int n, m, k; cin >> n >> m >> k;for (int i = 1; i <= n; i++) {for (int j = 1; j <= m; j++) {cin >> a[i][j];}}for (int i = 1; i <= m; i++) {for (int j = 1; j <= k; j++) {cin >> b[i][j];}}for (int i = 1; i <= n; i++) {for (int j = 1; j <= k; j++) {for (int p = 1; p <= m; p++) {c[i][j] += a[i][p] * b[p][j];}}}for (int i = 1; i <= n; i++) {for (int j = 1; j <= k; j++) {cout << c[i][j] << " ";}cout << endl;}return 0;
}