๐ฉ๐ปโ๐ป๋ฌธ์ ๋งํฌ
[ํ๋ก๊ทธ๋๋จธ์ค 43165] ํ๊ฒ ๋๋ฒ (Javascript)
โ๏ธIdea Sketch
2021-07-13
1. ๋ฌธ์ ์ดํด
- ๋ํ๊ธฐ ๋นผ๊ธฐ ๋๊ฐ์ง ์ฐ์ฐ
2. ๋ก์ง
- DFS
- numbers์ ์์๋ฅผ ๋ํ๋ ๊ฒฝ์ฐ or ๋นผ๋ ๊ฒฝ์ฐ
3. DFS
- ์ข ๋ฃ์กฐ๊ฑด : v === numbers.length ์ธ ๊ฒฝ์ฐ
sum += numbers[v]; // v๋ฒ์งธ ์์๋ฅผ ๋ํ๋ ๊ฒฝ์ฐ
DFS(v+1);
sum -= numbers[v]*2; // v๋ฒ์งธ ์์๋ฃฐ ๋นผ๋ ๊ฒฝ์ฐ
DFS(v+1);
sum += numbers[v]; // ์๋ณต
โ๏ธ์์ค์ฝ๋
2021-07-13 ์ ํ์ฑ ํต๊ณผ
function solution(numbers, target) {
let cnt = 0;
let sum = 0;
function DFS(v) {
if (v === numbers.length) {
if (sum === target) cnt++;
return;
}
sum += numbers[v];
DFS(v+1);
sum -= numbers[v]*2;
DFS(v+1);
sum += numbers[v];
}
DFS(0);
return cnt;
}
โ๏ธ๋ช ๋ต
DFS getAnswer() ํจ์์ ๋งค๊ฐ๋ณ์์ sum์ ํฌํจํ๋ ๊ฒ์ด ๋ ์ง๊ด์
function solution(numbers, target) {
let answer = 0;
getAnswer(0,0);
function getAnswer(x, value) { // sum ๋์ value ์ฌ์ฉ
if(x<numbers.length){
getAnswer(x+1,value + numbers[x]);
getAnswer(x+1,value - numbers[x]);
} else{
if(value === target){
answer++
}
}
}
return answer;
}