Blue Bridge cup of java basic training Triangle

Basic training Triangle

Resource constraints

Time limit: 1.0s Memory Limit: 256.0MB

Problem Description

Triangle known as Pascal triangle, its first row i + 1 is (a + b) i-expanding coefficient.

It is an important property: triangles each number equal to its two shoulders numbers together.

We are given below of the first four rows Triangle:

1

1 1

1 2 1

1 3 3 1

Given n, the first n rows outputs it.

Input Format

Input contains a number n.

Output Format

The output of the first n rows Triangle. Each row from the first row are sequentially output number, using one intermediate spaces. Please do not print extra spaces in front.

import java.util.Scanner;
public class Main {
    public static void main(String[] args) {
        
        Scanner scanner=new Scanner(System.in);
        int n=scanner.nextInt()+1;
        int[][] array=new int[n][n];
        for(int i=0;i< n; i++){
            array[i][1]=1;
            array[i][i]=1;
        }
        for(int j=2;j<n;j++){
            for(int k = 2;k < n;k++){
                array[j][k]=array[j-1][k]+array[j-1][k-1];
            }
        }
        for (int i = 1; i < array.length; i++) {
            for (int j = 1; j < array.length; j++) {
                if(array[i][j]>0){
                    System.out.print(array[i][j]+" ");                  
                }
            }
            System.out.println();
        }
    }
    
}
Published 24 original articles · won praise 2 · Views 188

Guess you like

Origin blog.csdn.net/weixin_44570019/article/details/104515507