Skip to content

Commit 3a08efa

Browse files
committed
114차 1번 문제풀이
1 parent cd62198 commit 3a08efa

1 file changed

Lines changed: 54 additions & 0 deletions

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
const input = require("fs")
2+
.readFileSync(
3+
process.platform === "linux"
4+
? "/dev/stdin"
5+
: require("path").join(__dirname, "input.txt"),
6+
"utf8"
7+
)
8+
.trim();
9+
10+
const LEFT_PAREN = "(";
11+
const RIGHT_PAREN = ")";
12+
13+
function solution(expr) {
14+
const stack = [];
15+
const pairs = [];
16+
17+
for (let i = 0; i < expr.length; i++) {
18+
if (expr[i] === LEFT_PAREN) {
19+
stack.push(i);
20+
} else if (expr[i] === RIGHT_PAREN) {
21+
const openIdx = stack.pop();
22+
pairs.push([openIdx, i]);
23+
}
24+
}
25+
26+
const results = new Set();
27+
const total = pairs.length;
28+
29+
const dfs = (depth, selected) => {
30+
if (depth === total) {
31+
if (selected.length === 0) return;
32+
33+
const toRemove = new Set(selected.flat());
34+
let str = "";
35+
for (let i = 0; i < expr.length; i++) {
36+
if (!toRemove.has(i)) {
37+
str += expr[i];
38+
}
39+
}
40+
results.add(str);
41+
return;
42+
}
43+
44+
dfs(depth + 1, [...selected, pairs[depth]]);
45+
dfs(depth + 1, selected);
46+
};
47+
48+
dfs(0, []);
49+
50+
const sorted = [...results].sort();
51+
return sorted.join("\n");
52+
}
53+
54+
console.log(solution(input));

0 commit comments

Comments
 (0)