프로그래머스

프로그래머스 lvl 2. 타겟 넘버 [C++]

soobinida 2023. 8. 17. 16:15

n개의 음이 아닌 정수들이 있습니다. 이 정수들을 순서를 바꾸지 않고 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다.

-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3

 

사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요.

 

 

접근 point

  • bfs/dfs 알고리즘

알고리즘 설명

 

Index 0 부터 시작하여 Index가 '배열 사이즈 - 1'을 도달 할 때 까지 + 혹은 - 로 계산하여, target number가 될 경우 count를 올려주는 방식이다. 

 

 

#include <bits/stdc++.h>
using namespace std;

int cnt = 0; // target count 용도


void dfs(vector<int> numbers, int target, int idx, int sum) {
    if(idx == numbers.size()-1) { // 배열의 마지막 index 도달
        if(sum == target) cnt++; // target이 되었을 때 cnt 올리기
        return;
    }
    dfs(numbers, target, idx+1, sum+numbers[idx+1]);
    dfs(numbers, target, idx+1, sum-numbers[idx+1]);
}

int solution(vector<int> numbers, int target) {
    dfs(numbers, target, 0, numbers[0]);
    dfs(numbers, target, 0, -numbers[0]);
    return cnt;
}