문제
9095번: 1, 2, 3 더하기
각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 출력한다.
www.acmicpc.net
구현 방법
점화식을 구해준 다음 bottom-up 방식으로 반복문을 돌려 구해주었습니다.
n이 1일 때 1, n이 2일 때 2, n이 3일 때 4, n이 4일 때 7이므로 n일 때 dp[n] = dp[n-1]+dp[n-2]+dp[n-3] 임을 알 수 있습니다.
구현 코드
package BOJ.Silver;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ9095_123더하기 {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
int TC = Integer.parseInt(br.readLine());
for (int tc=1;tc<=TC;tc++) {
int N = Integer.parseInt(br.readLine());
int[] dp = new int[N+1];
dp[1] = 1;
if(N>1) dp[2] = 2;
if(N>2) dp[3] = 4;
for (int i=4;i<=N;i++) {
dp[i] = dp[i-1]+dp[i-2]+dp[i-3];
}
sb.append(dp[N]+"\n");
}
System.out.println(sb);
}
}
'백준' 카테고리의 다른 글
백준 1463번 : 1로 만들기 (0) | 2021.03.19 |
---|---|
백준 9461번 : 파도반 수열 (0) | 2021.03.19 |
백준 1010번 : 다리 놓기 (0) | 2021.03.19 |
백준 1003번 : 피보나치 함수 (0) | 2021.03.19 |
백준 2210번 : 숫자판 점프 (0) | 2021.03.18 |