문제
정수 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의 합으로 나타내는 방법의 수를 구하는 프로그램을 작성하시오.
출력
각 테스트 케이스마다, n을 1, 2, 3의 합으로 나타내는 방법의 수를 출력한다.
W3sicHJvYmxlbV9pZCI6IjkwOTUiLCJwcm9ibGVtX2xhbmciOiIwIiwidGl0bGUiOiIxLCAyLCAzIFx1YjM1NFx1ZDU1OFx1YWUzMCIsImRlc2NyaXB0aW9uIjoiPHA+XHVjODE1XHVjMjE4IDRcdWI5N2MgMSwgMiwgM1x1Yzc1OCBcdWQ1NjlcdWM3M2NcdWI4NWMgXHViMDk4XHVkMGMwXHViMGI0XHViMjk0IFx1YmMyOVx1YmM5NVx1Yzc0MCBcdWNkMWQgN1x1YWMwMFx1YzljMFx1YWMwMCBcdWM3ODhcdWIyZTQuIFx1ZDU2OVx1Yzc0NCBcdWIwOThcdWQwYzBcdWIwYmMgXHViNTRjXHViMjk0IFx1YzIxOFx1Yjk3YyAxXHVhYzFjIFx1Yzc3NFx1YzBjMSBcdWMwYWNcdWM2YTlcdWQ1NzRcdWM1N2MgXHVkNTVjXHViMmU0LjxcL3A+XHJcblxyXG48dWw+XHJcblx0PGxpPjErMSsxKzE8XC9saT5cclxuXHQ8bGk+MSsxKzI8XC9saT5cclxuXHQ8bGk+MSsyKzE8XC9saT5cclxuXHQ8bGk+MisxKzE8XC9saT5cclxuXHQ8bGk+MisyPFwvbGk+XHJcblx0PGxpPjErMzxcL2xpPlxyXG5cdDxsaT4zKzE8XC9saT5cclxuPFwvdWw+XHJcblxyXG48cD5cdWM4MTVcdWMyMTggblx1Yzc3NCBcdWM4ZmNcdWM1YjRcdWM4NGNcdWM3NDQgXHViNTRjLCBuXHVjNzQ0IDEsIDIsIDNcdWM3NTggXH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6IjxwPlByaW50IGV4YWN0bHkgb25lIGxpbmUgZm9yIGVhY2ggdGVzdCBjYXNlLiBUaGUgbGluZSBzaG91bGQgY29udGFpbiBhbiBpbnRlZ2VyIHJlcHJlc2VudGluZyB0aGUgbnVtYmVyIG9mIHdheXMuPFwvcD5cclxuIiwiaGludCI6IiIsIm9yaWdpbmFsIjoiMSIsImh0bWxfdGl0bGUiOiIwIiwicHJvYmxlbV9sYW5nX3Rjb2RlIjoiRW5nbGlzaCJ9XQ==
접근 방법
- n이 4이상일 때, 다음과 같이 식을 추론할 수 있다. an = (1 + an-1) + (2 + an-2) + (3 + an-3)
- n이 4이상일 때, n을 1, 2, 3의 합으로 나타내는 방법은 다음과 같이 표현할 수 있다. An = A(n-1) + A(n-2) + A(n-3)
- 위의 일반항을 토대로 다이나믹 프로그래밍을 진행한다.
코드
# https://www.acmicpc.net/problem/9095 # 접근 방법 # n이 4이상일 때, 다음과 같이 식을 추론할 수 있다. an = (1 + an-1) + (2 + an-2) + (3 + an-3) # n이 4이상일 때, n을 1, 2, 3의 합으로 나타내는 방법은 다음과 같이 표현할 수 있다. An = A(n-1) + A(n-2) + A(n-3) # 위의 일반항을 토대로 다이나믹 프로그래밍을 진행한다. def find_count(n): if d[n]: return d[n] d[n] = find_count(n-1) + find_count(n-2) + find_count(n-3) return d[n] d = [0 for _ in range(11)] d[1] = 1 d[2] = 2 d[3] = 4 tc = int(input()) for _ in range(tc): n = int(input()) print(find_count(n))