1, 2, 3 더하기

Huisu·2023년 10월 16일
0

Coding Test Practice

목록 보기
48/98
post-thumbnail

문제

9095번: 1, 2, 3 더하기

문제 설명

정수 4를 1, 2, 3의 합으로 나타내는 방법은 총 7가지가 있다. 합을 나타낼 때는 수를 1개 이상 사용해야 한다.

  • 1+1+1+1
  • 1+1+2
  • 1+2+1
  • 2+1+1
  • 2+2
  • 1+3
  • 3+1

정수 n이 주어졌을 때, n을 1, 2, 3의 합으로 나타내는 방법의 수를 구하는 프로그램을 작성하시오.

제한 사항

첫째 줄에 테스트 케이스의 개수 T가 주어진다. 각 테스트 케이스는 한 줄로 이루어져 있고, 정수 n이 주어진다. n은 양수이며 11보다 작다.

각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 출력한다.

입출력 예

입력출력
3
47
744
10274

제출 코드


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class three9095 {
    static int[] dp = new int[13];
    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        int testCase = Integer.parseInt(reader.readLine());
        for (int i = 0; i < testCase; i++) {
            int number = Integer.parseInt(reader.readLine());
            System.out.println(plusCombination(number));
        }
    }

    private int plusCombination(int number) {
        if (number == 1) return 1;
        if (number == 2) return 2;
        if (number == 3) return 4;
        dp[number] = plusCombination(number - 1) // + 1 한 경우
        + plusCombination(number - 2) // + 2 한 경우
        + plusCombination(number - 3);
        return dp[number];
    }

    public static void main(String[] args) throws IOException {
        new three9095().solution();
    }
}

0개의 댓글