티스토리 뷰


title: "타겟 넘버"
category: 프로그래머스[Level-2]
tags: [C++, JavaScript, 프로그래머스]
date: "2021-01-28"


문제 링크

타겟 넘버

C++

#include <string>
#include <vector>
#include <algorithm>

using namespace std;

void dfsGo(vector<int>& numbers, int& tgt, int& asr, int sum, int level){
    if(level==numbers.size()) {
        if(tgt==sum) asr++;
    }
    else{
        dfsGo(numbers, tgt, asr, sum+numbers[level], level+1);  // +
        dfsGo(numbers, tgt, asr, sum-numbers[level], level+1);  // -
    }
}

int solution(vector<int> numbers, int target) {
    int answer = 0;

    dfsGo(numbers, target, answer, numbers[0], 1);  // +
    dfsGo(numbers, target, answer, -numbers[0], 1); // -

    return answer;
}

JavaScript

function solution(numbers, target) {
  var answer = 0;

  const dfsGo = (sum, level) => {
    if (level === numbers.length) {
      if (sum === target) answer++;
    } else {
      dfsGo(sum + numbers[level], level + 1); // +
      dfsGo(sum - numbers[level], level + 1); // -
    }
  };

  dfsGo(numbers[0], 1); // +
  dfsGo(-numbers[0], 1); // -

  return answer;
}
728x90
반응형
댓글
01-10 09:46
링크