Design and Analysis of Algorithms 2.2 draw a triangle

★ Title Description

Draw programmed size N triangle.

1 triangular scale as shown in the sample.

X is the size of three triangle triangular X-1 scale the mosaic, as shown in the sample.

★ input format

An integer N, the size of the triangle. To 100% of the data, 1 <= N <= 10.

★ output format

Draw the corresponding triangle, pay attention to the last valid character directly after a carriage return, do not print extra spaces.

★ Sample input 1

1

★ Sample output 1

 /\
/__\

★ Sample input 2

2

★ sample output 2

   /\
  /__\
 /\  /\
/__\/__\

★ Tips

/*
3
       /\   0
      /__\  1
     /\  /\    2
    /__\/__\   3
   /\      /\    4
  /__\    /__\   5
 /\  /\  /\  /\    6
/__\/__\/__\/__\   7

使用字符数组
每次迭代创建一个新的字符数组 
然后实现每次图案的时候从最底层往上 
*/

#include<iostream>
#include<string.h>
using namespace std;
string sj[1024] = {" /\\", "/__\\"};

void dfs(int n){
    int step = (1<<n-1);
    for(int i=2*step-1; i>=step; --i){
        sj[i] = sj[i-step];
        for(int j=1; j<2*step-i; j++) sj[i]+=" ";
        sj[i] += sj[i-step];
    }
    string tmp;
    for(int i=step-1; i>=0; --i){
        tmp = "";
        for(int j=1; j<=step; j++) tmp+=" ";
        sj[i] = tmp + sj[i];
    }
}

int main(){
    int n;
    cin>>n;
    
    for(int i=2; i<=n; i++) dfs(i);
    
    for(int i=0; i<=(1<<n)-1; ++i){
        cout<<sj[i]<<endl;
    }
    return 0;
}
 

Guess you like

Origin www.cnblogs.com/yejifeng/p/12044404.html