我的代码:
#include<bits/stdc++.h>
using namespace std;
const int N=1000;
int n;
char s[N][N];
void work(int x)
{if(x==1) {s[0][0]='*';return;}work(x-1);for(int i=0;i<(1<<x-2);i++)for(int j=(1<<x-2);j<(1<<x-1);j++) s[i][j]=s[i][j-(1<<x-2)];for(int i=(1<<x-2);i<(1<<x-1);i++)for(int j=0;j<(1<<x-2);j++) s[i][j]=s[i-(1<<x-2)][j];for(int i=(1<<x-2);i<(1<<x-1);i++)for(int j=(1<<x-2);j<(1<<x-1);j++) s[i][j]=' ';
}
int main()
{scanf("%d",&n);work(n);for(int i=0;i<(1<<n-1);i++) {int j=1<<n-1;j--;while(s[i][j]!='*') j--;for(int k=0;k<j;k++) printf("%c ",s[i][k]);printf("%c",s[i][j]);if(i!=(1<<n-1)-1) printf("\n");}return 0;
}
另一种实现思路
#include <iostream>
using namespace std;
void draw_triangle(int n, int x, int y);
int main()
{
int n;
cin >> n;
for(int i=0; i<65; i++){
for(int j=0; j<65; j++){
grid[i][j] = ' ';
}
}
draw_triangle(n, 0, 0);
for(int i=0; i<sizes[n]; i++){
for(int j=0; j<sizes[n]-i; j++){
if(j+1==sizes[n]-i){
cout << grid[i][j] << endl;;
}else{
cout << grid[i][j] << " ";
}
}
}
return 0;
}
int sizes[] = {0, 1, 2, 4, 8, 16, 32, 64};
char grid[65][65];
void draw_triangle(int n, int x, int y){
if(n==1){
grid[x][y] = '*';
return;
}
draw_triangle(n-1, x, y);
draw_triangle(n-1, x+sizes[n-1], y);
draw_triangle(n-1, x, y+sizes[n-1]);
}
这两种思路都要会