[BOJ] 백준 14888 - 연산자끼워넣기

note.JW·2020년 12월 30일
1

Algorithm

목록 보기
1/10
post-thumbnail

14888번 문제 풀이

using Java 11

14888번 문제 보기

import java.util.Scanner;

public class boj14888 {
	public static int N;
	public static int[] nums;
	public static int[] op = new int[4];
	public static int MAX = Integer.MIN_VALUE;
	public static int MIN = Integer.MAX_VALUE;
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		N = in.nextInt();
		nums = new int[N];
		for(int i = 0; i < N; i++) {
			nums[i] = in.nextInt();
		}
		for(int i = 0; i < 4; i++) {
			op[i] = in.nextInt();
		}
		findMax(1, nums[0]);
		
		System.out.println(MAX);
		System.out.println(MIN);
	}
	
	public static void findMax(int depth, int num) {
		if(depth == N) {
			MAX = Math.max(MAX, num);
			MIN = Math.min(MIN, num);
			return;
		}
		
		for(int i = 0; i < 4; i++) {
			if(op[i] > 0) {
				op[i]--;
				switch(i){
					case 0: findMax(depth + 1,num + nums[depth]); break;
					case 1: findMax(depth + 1,num - nums[depth]); break;
					case 2: findMax(depth + 1,num * nums[depth]); break;
					case 3: findMax(depth + 1, (int)(num / nums[depth])); break;
				}
				op[i]++;
			}
		}
	}

}

📍 백트랙킹과 재귀호출을 사용하여 문제를 해결했다.

틀린 이유
연산자를 사용해서 op[i]-- 하고 나서 case 문 만들다가 op[i]++ 을 까먹어서 답이 제대로 안나왔다.
재귀호출 할 때 꼭 이렇게 한 줄씩 빼먹으면 디버깅할 때 고생한다 😂😂

profile
🎆우주란 무엇일까🎆

1개의 댓글

comment-user-thumbnail
2020년 12월 30일

잘 보고 갑니다~!

답글 달기