백준 1904

旅人·2023년 2월 26일

문제


Code

package test;

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

public class P1904 {

	// dp[N] : 길이 N인 2진 수열 개수
	private static int[] dp = new int[1000001];
	
	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
		int N = Integer.parseInt(br.readLine());
		
		// initial values
		dp[1] = 1; // 1
		dp[2] = 2; // 11, 00
		
		
		System.out.println(countAll(N));
		

	}
	
	//	길이 N인 2진 수열 개수 구하기
	private static int countAll(int N) {
		// 아직 개수 계산 안해봤을 때 
		if(N > 2  && dp[N] == 0) {
			
			/*
			 길이가 N(>= 3)인 수열의 맨앞은 반드시 1로 시작하거나 00으로 시작한다. 
			 
			 1) 맨 앞이 1로 시작할 때 --> 나머지 길이 N - 1인 2진 수열 찾기
			 2) 맨 앞이 00로 시작할 때 --> 나머지 길이 N - 2인 2진 수열 찾기 
			 */
			
			dp[N] = countAll(N - 1) + countAll(N - 2);
			dp[N] %= 15746;
		}
		// 이미 계산해봤으면 dp에서 찾아서 반환
		return dp[N];
	}

}

참고 : https://st-lab.tistory.com/125

profile
一期一会

0개의 댓글