[BaekJoon] #1904 - 01타일 [Java][C++]
[BaekJoon] #1904 - 01타일 [Java][C++]
1. 아이디어
00과 1을 활용해서 만들 수 있는 $N$자리 수열의 개수를 구하는 문제로, $N$자리 수열의 끝은 00이거나 1인 두 가지밖에 없는데, 00이 오는 경우는 $N - 2$자리에서 00을 붙이는 경우만큼 존재하며, 1이 오는 경우는 $N - 1$자리에서 1을 붙이는 경우만큼 존재한다. 따라서 두 경우의 합만큼이 $N$자리 수열을 만드는 개수가 된다.
2. 복잡도
| 접근 | 시간 | 공간 |
|---|---|---|
| 풀이 | $O(N)$ | $O(N)$ |
($N$ = 입력값 n)
3. 코드
풀이 [Java][C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import java.io.*;
public class Main {
static final int MOD = 15746;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
if (n == 1) {
System.out.println(1);
return;
}
int[] dp = new int[1 + n];
dp[1] = 1;
dp[2] = 2;
for (int i = 3; i <= n; i++) {
dp[i] = (dp[i - 2] + dp[i - 1]) % MOD;
}
System.out.println(dp[n]);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <bits/stdc++.h>
using namespace std;
const int MOD = 15746;
int dp[1 + 1'000'000] = {0, 1, 2};
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin >> n;
for (int i = 3; i <= n; i++) {
dp[i] = (dp[i - 2] + dp[i - 1]) % MOD;
}
cout << dp[n];
}
This post is licensed under CC BY 4.0 by the author.