首页 > 解决方案 > 如何递归地做我的金字塔数字模式?

问题描述

我必须使用递归方法制作这种模式我让它在 main 中打印出不正确的数字我这样称呼它 int n = 5; a.模式(n,n);

    static void print_space(int space) 
{ 
    // base case 
    if (space == 0) 
        return; 
    System.out.print(" "); 

    // recursively calling print_space() 
    print_space(space - 1); 
} 

// function to print numbers 
static void print_numbers(int numbers) 
{ 
    // base case 
    if (numbers == 0) 
        return; 
    System.out.print("1 "); 

    // recursively calling numbers() 
    print_numbers(numbers - 1); 
} 

// function to print the pattern 
static void pattern(int n, int num) 
{ 
    // base case 
    if (n == 0) 
        return; 
    print_space(n - 1); 
    print_numbers(num - n + 1); 
    print_numbers(num - n); 
    System.out.println(""); 

    // recursively calling pattern() 
    pattern(n - 1, num); 
} 
}

最后应该是这样的,但我有这样的

    1                          1
   212                        211
  32123                      32121
                            4321321

等等......谢谢!

标签: java

解决方案


这个金字塔...

*********1*********
********212********
*******32123*******
******4321234******
*****543212345*****
****65432123456****
***7654321234567***
**876543212345678**
*98765432123456789*

... 是这种递归方法的结果,没有空格和数字的方法:

public class RecursivePyramid {

    public static void WriteOutPyramidLevel(int level,int height) {

        // Need counter in loops 
        int counter;

        // Writing spaces in front - using asterix for visible debugging
        for (counter=height ;counter > level; counter-- ) 
          System.out.print("*");

        // Writing numbers in front
        for (counter=level ;counter > 1; counter-- ) 
            System.out.print(counter);                    

        // Writing central «line» in Pyramid    
        System.out.print(1);

        // Writing numbers after central line
        for (counter=2 ;counter <= level; counter++ ) 
            System.out.print(counter);

        // Writing spaces after central line - can of course be removed   
        for (counter=level ;counter < height; counter++) 
            System.out.print("*"); 

        // Line finished
        System.out.println();

        // If below height of Pyramid go again - max 9 allowed 
        if (level < height && level < 9)
          WriteOutPyramidLevel(level+1,height);        
    }

    public static void main(String[] parameters) {

        WriteOutPyramidLevel(1,10);        
    }
}


推荐阅读