๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[์ธํ๋ฐ ์น์
8] ํฉ์ด ๊ฐ์ ๋ถ๋ถ์งํฉ (Javascript)
์ ๋ฃ ๊ฐ์์ธ ๊ด๊ณ๋ก ๋ฌธ์ ์ค๋ช
์ ์๋ตํฉ๋๋ค.
โ๏ธIdea Sketch
2021-06-29
1. (์งํฉ์ ํฉ === ์ ์ฒด ์งํฉ์ ํฉ - ์งํฉ์ ํฉ) ์ธ์ง ํ์ธํ์ฌ true๋ฉด "YES", false๋ฉด "NO"
- ํ ๋ฒ์ด๋ผ๋ ์กฐ๊ฑด์ ๋ง์กฑํ๋ฉด ์ ์ฒด์ข ๋ฃ
if (n >= arr.length) {
let sum = res.reduce((a, b) => a + b, 0);
if (su)
}
2. ๋ถ๋ถ์งํฉ์ ํฉ ๊ตฌํ๋ 2๊ฐ์ง ๋ฐฉ๋ฒ
- ๋ฐฉ๋ฒ 1. res.push(), res.pop()
let res = [];
let total = arr.reduce((a, b) => a + b, 0);
function DFS(n) {
if (n >= arr.length) {
let sum = res.reduce((a, b) => a + b, 0);
if (sum === total - sum) return "YES"
}
res.push(arr[n]);
DFS(n+1);
}
- ๋ฐฉ๋ฒ 2. sum += n, sum -= n
let sum = 0;
let total = arr.reduce((a, b) => a + b, 0);
function DFS(n) {
if (n >= arr.length) {
if (sum === total - sum) return "YES";
}
sum += arr[n];
DFS(n+1);
sum -= arr[n];
DFS(n+1);
}
3. ํ ๋ฒ์ด๋ผ๋ ์กฐ๊ฑด์ ๋ง์กฑํ๋ฉด ์ ์ฒด์ข ๋ฃํ๋ ๋ฐฉ๋ฒ
- return flag ์์ฑ
- DFS ๋ด๋ถ์์ flag = true/false
- DFS ์ธ๋ถ์์ flag ๊ฐ์ ๋ฐ๋ผ YES/NO ์ถ๋ ฅ
let flag = false;
function DFS (n) {
if (flag) return;
else {}
}
DFS(0);
console.log(flag ? "YES" : "NO");
โ๏ธ์์ค์ฝ๋
2021-06-29
let arr = [1, 3, 5, 6, 7, 10];
let total = arr.reduce((a, b) => a + b, 0);
let sum = 0;
let flag = false;
function DFS(n) {
if (flag) return;
if (n >= arr.length) {
if (sum === total - sum) flag = true;
return;
}
sum += arr[n];
DFS(n + 1);
sum -= arr[n];
DFS(n + 1);
}
DFS(0);
console.log(flag ? "YES" : "NO");