CodingTEST

[SW Expert D2] 2005. 파스칼의 삼각형

경걍 2023. 11. 13. 16:05
반응형

2005. 파스칼의 삼각형

 

SW Expert Academy

SW 프로그래밍 역량 강화에 도움이 되는 다양한 학습 컨텐츠를 확인하세요!

swexpertacademy.com

 

 

문제 분석

 

  • N을 입력 받으면 크기가 N인 파스칼의 삼각형을 만들어라 
  • 파스칼의 삼각형 규칙
    • 첫 번째 줄은 항상 숫자 1
    • 두번째 줄부터 각 숫자들의 값은 [왼쪽 위 + 오른쪽 위] 이다

 

해결 키 포인트

 

  • 크기는 10개까지이고 시간은 30초이다 (매우 넉넉)
  • 부모의 합으로 값이 정해진다는 규칙이 있으므로 부모 숫자 배열을 제작 : parentNum
    • 구하기 쉽게 부모 값의 len은 [숫자 개수 + 2]로 설정
    • 현재 값 = 왼쪽부모 + 오른쪽부모 : currentNum[j] = parentNum[j-1] + parentNum[j]
    • 값이 0이 아닌 숫자를 빈칸을 사이에 두고 출력 : 0인 숫자가 존재하는 이유는 len을 [숫자 개수 + 2]로 설정하였기 때문
    • 다음 자식의 값을 구하기위해 현재 값을 부모 값으로 변경

 

코드

 

import java.util.Arrays;
import java.util.Scanner;

class Solution
{
    public static void main(String args[]) throws Exception
    {
        Scanner sc = new Scanner(System.in);
        int T;
        T=sc.nextInt();

        for(int test_case = 1; test_case <= T; test_case++)
        {
            int N = sc.nextInt();

            int [] parentNum = new int[2];
            parentNum[0] = 1;

            System.out.println("#" + test_case);

            for(int i=1;i<=N;i++) {
                int [] currentNum = new int [i+2];
                for(int j=1;j<=i;j++) {
                    currentNum[j] = parentNum[j-1] + parentNum[j];
                }

                Arrays.stream(currentNum).forEach(n -> printNums(n));
                System.out.println();

                parentNum = currentNum;
            }
        }
    }

    public static void printNums(int n) {
        if(n > 0)
            System.out.print(n+" ");
    }
}
반응형