[16922번] 로마 숫자 만들기 ( 조합, 재귀 )

Loopy·2023년 12월 11일
0

코테 문제들

목록 보기
54/113

이 문제를 딱 보자마자 뽑는 갯수가 더 많다고?
그러면 뽑는 갯수를 n으로 생각하고 문제를 접근해보자. 라는 생각이 들었다.


✅ 시간초과

아마도 2차원 boolean 배열 때문인듯!

import java.util.Scanner;

public class BJ16922_로마숫자만들기 {
	static int N;
	static int num[];
	static int sum[];
	static int res;
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		N = sc.nextInt();
		num = new int []{1, 5, 10, 50};
		sum = new int [10000];
		pick(0, 0, 0);
		System.out.println(res);
	}
	
	static void pick(int cnt, int idx, int s) {
		if(cnt == N) {
			if(sum[s] == 0) {
				sum[s] = 1;
				res++;
			}
			return;
		}
	
		for (int i = idx; i < 4; i++) {
			pick(cnt + 1, i, s + num[i]);
		}
	}
}

✅ 재귀

for (int i = index; i < 4; i++) {
			pick(n - 1, i, sum + num[i]);
		}

✅ 코드

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

public class Main {

	static int[] num = {1, 5, 10, 50};
	static boolean[] dp = new boolean[1001];
	static int result = 0, N = 0;

	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		N = Integer.parseInt(br.readLine());
		pick(N, 0, 0);
		System.out.println(result);
	}

	private static void pick(int n, int index, int sum) {
		if (n == 0) {
			if (dp[sum] == false) {
				result++;
				dp[sum] = true;
			}
			return;
		}

		for (int i = index; i < 4; i++) {
			pick(n - 1, i, sum + num[i]);
		}

	}


}

https://tussle.tistory.com/832

profile
잔망루피의 알쓸코딩

0개의 댓글