코딩테스트(알고리즘)/baekjoon
[baekjoon] 16637 괄호 추가하기 (Javascript)
Cafe Mocha
2023. 2. 2. 16:42
16637번: 괄호 추가하기
첫째 줄에 수식의 길이 N(1 ≤ N ≤ 19)가 주어진다. 둘째 줄에는 수식이 주어진다. 수식에 포함된 정수는 모두 0보다 크거나 같고, 9보다 작거나 같다. 문자열은 정수로 시작하고, 연산자와 정수가
www.acmicpc.net
알고리즘 : 재귀
이건 내가 푼 문제가 아니다 ㅠㅠ
재귀는 이해는 할 수 있는데 직접 짜려고하면 도저히 이해가 안간다...
const calc = (oper, a, b) => {
if (oper === "+") return a + b;
if (oper === "-") return a - b;
if (oper === "*") return a * b;
};
function solution() {
let input = require("fs")
.readFileSync("input.txt") //"/dev/stdin"
.toString()
.split("\n")
.map((val) => val.trim());
let n = +input.shift();
let arr = input.shift().split("");
// 최대값
let ans = -999999999999;
// 연산자는 +,-,*
// 괄호...흠...?
let num = [];
let oper = [];
for (let i = 0; i < n; i++) {
if (i % 2 === 0) num.push(arr[i]);
else oper.push(arr[i]);
}
num = num.map((v) => +v);
console.log(num, oper);
const check = (here, number) => {
console.log(here, number);
if (here === num.length - 1) {
ans = Math.max(ans, number);
return;
}
check(here + 1, calc(oper[here], number, num[here + 1]));
if (here + 2 <= num.length - 1) {
let temp = calc(oper[here + 1], num[here + 1], num[here + 2]);
check(here + 2, calc(oper[here], number, temp));
}
};
check(0, num[0]);
console.log(ans);
}
solution();