From e3b566040c1204233add8a146b83bc068236fe38 Mon Sep 17 00:00:00 2001 From: luckylooky2 Date: Tue, 10 Oct 2023 17:32:31 +0900 Subject: [PATCH] =?UTF-8?q?10.10:=20backtracking(=EB=B6=80=EB=B6=84?= =?UTF-8?q?=EC=88=98=EC=97=B4=EC=9D=98=20=ED=95=A9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- baekjoon/1182.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 baekjoon/1182.js diff --git a/baekjoon/1182.js b/baekjoon/1182.js new file mode 100644 index 0000000..9588c12 --- /dev/null +++ b/baekjoon/1182.js @@ -0,0 +1,35 @@ +// 부분수열의 합 : 백트래킹, 브루트 포스 +const input = require("fs") + .readFileSync("/dev/stdin") + .toString() + .trim() + .split("\n") + .map((v) => v.split(" ").map((v) => parseInt(v, 10))); +const [n, s] = input.shift(); +const arr = input.shift(); +const visited = []; +let answer = 0; +let total = 0; + +function isIncluded(num) { + for (let i = 0; i < visited.length; i++) if (visited[i] === num) return true; + return false; +} + +function recur(depth = 0) { + if (total === s && depth > 0) answer++; + if (depth === n) return; + + for (let i = 0; i < n; i++) { + if (isIncluded(i) || visited[visited.length - 1] >= i) continue; + visited.push(i); + total += arr[i]; + recur(depth + 1); + visited.pop(); + total -= arr[i]; + } +} + +recur(); + +console.log(answer);