차곡차곡 성 쌓기
article thumbnail

1. 💎 문제

 

 

2. 🤔 어떻게 풀까?

그림을 그려보니 가장자리는 무조건 1이고, 중간에 있는 요소들은 위에 있는 요소들을 순서대로 더하면 되는거였다.

그래서 처음에 ArrayList 배열로 구현할까 했지만, 이차원 배열로 구현하는게 더 좋은 방법같았다. 루프를 돌면서 차례대로 값을 채우기 위해서는 비어있는 값은 0으로 처리해야 했는데 ArrayList를 사용하면 0를 넣어주기도 애매하고 훨씬 어려워질 것 같아서, 애초에 처음부터 0으로 초기화되는 이차원 배열을 사용하기로 했다.

 

이렇게 0번째 요소에는 0를 담아 따로 에외처리를 하지 않도록 하였고, 순서대로 더 해주자고 생각했다.

`A[i+1] = A-1[i] + A-1[i+1]`를 적용하도록 생각 후 구현을 시작했다.

 

 

3. 💡 로직

1. 솔루션

파스칼 법칙을 적용하여 요소들을 알아낸다.

	int N = sc.nextInt();
            int [][] list = new int[N+1][N+1];
            list[1][1] = 1;

            for(int i=2; i<=N; i++){
                for(int j=0; j<i;j++){
                    list[i][j+1] = list[i-1][j] + list[i-1][j+1];
                }
            }

 

2. 출력

출력 조건에 맞도록 출력한다.

 	System.out.println(String.format("#%d", test_case));
            for(int i=1; i<=N; i++){
                for(int j=1; j<=i; j++){
                    System.out.print(list[i][j] + " ");
                }
                System.out.println();
            }

 

 

4. 📄 전체 코드

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 [][] list = new int[N+1][N+1];
            list[1][1] = 1;

            for(int i=2; i<=N; i++){
                for(int j=0; j<i;j++){
                    list[i][j+1] = list[i-1][j] + list[i-1][j+1];
                }
            }


           System.out.println(String.format("#%d", test_case));
            for(int i=1; i<=N; i++){
                for(int j=1; j<=i; j++){
                    System.out.print(list[i][j] + " ");
                }
                System.out.println();
            }


        }
    }
728x90
profile

차곡차곡 성 쌓기

@nagrang

포스팅이 좋았다면 "좋아요" 해주세요!