SIU
article thumbnail

문제 유형

https://school.programmers.co.kr/learn/courses/30/lessons/43165

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

 

문제 풀이

+, - 선택 (있거나 없거나) 
양자 택일은 dfs
또한, 연산 끝이(depth) 있다. (피연산자 개수만큼)

기저조건을 피연산자를 다 사용했을 때와 count 개수 세는 로직과 분리해야 한다. 

만약   if(count === numbers.length && sum === target) 이렇게 설계하면 함수 종료 return과 count 둘 중 하나가 안 돌아간다. (무한 호출 dfs)

 

 

전체 코드

function solution(numbers, target) {
   function dfs(count, sum) {
      // 피연산자를 다 사용했으면
     if(count === numbers.length){
      // 총합이 targer 하고 같은지 확인
       if(sum === target) answer++;
        return;
     }  
       let num = numbers[count]
       dfs(count+1,sum+num)
       dfs(count+1,sum-num)
   }  
    let answer = 0;  // function 안에 function 선언하면 전역변수로 사용가능  
    dfs(0,0)
    return answer;  
}

profile

SIU

@웹 개발자 SIU

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!