728x90
이 문제를 처음에 접할 때, 이차원 배열, 일차원 배열을 생각하면서 접근했다. 그런데 n = 1부터 n = 5까지 그림을 그리면서 하는데 규칙성이 보이게 됬다. 피보나치와 비슷한 규칙을 가지게 된다.
Top down
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
26
27
28
29
30
|
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int[] dp;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
dp = new int[N+1];
Arrays.fill(dp, -1);
System.out.print(tile(N));
}
public static int tile(int n){
if(n == 1) return 1;
if(n == 2) return 2;
if(dp[n] != -1) return dp[n];
dp[n] = (tile(n-1) + tile(n-2)) % 10007;
return dp[n];
}
}
|
cs |
Bottom up 방식
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
26
27
28
29
|
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.StringTokenizer;
public class Main {
static int[] dp;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int N = Integer.parseInt(st.nextToken());
dp = new int[N+1];
dp[0] = 1;
dp[1] = 1;
for(int i = 2; i <= N; i++) {
dp[i] = (dp[i-1] + dp[i-2]) % 10007;
}
System.out.print(dp[N]);
}
}
|
cs |
728x90
'BOJ(Java)' 카테고리의 다른 글
자바(백준) 1325 효율적인 해킹 (0) | 2020.10.26 |
---|---|
자바(백준) 2606 바이러스 (0) | 2020.10.06 |
자바(백준) 11057 오르막 수 (0) | 2020.09.28 |
자바(백준) 11726 2*N 타일링 2 (0) | 2020.09.28 |
자바(백준) 1463 1로 만들기 (0) | 2020.09.28 |