Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

Life Engineering

[프로그래머스] 타겟 넘버 (C++) 본문

Problem Solving

[프로그래머스] 타겟 넘버 (C++)

흑개 2021. 9. 23. 01:17

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

 

코딩테스트 연습 - 타겟 넘버

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

programmers.co.kr

 

#include <string>
#include <vector>

using namespace std;

int cnt=0;

void dfs(vector<int>& numbers, int target, int depth, int limit, int result){
    if (depth==limit){
        if (result==target){
            cnt++;
        }
        return;
    }
    dfs(numbers, target, depth+1, limit, result+numbers[depth]);
    dfs(numbers, target, depth+1, limit, result-numbers[depth]);
}

int solution(vector<int> numbers, int target) {
    dfs(numbers, target, 0, numbers.size(), 0);
    return cnt;
}

DFS 를 이용하여 탐색하는 문제.

 

1 depth마다 2가지 경우의 수가 존재한다.(더하느냐, 빼느냐).

DFS 방식으로 탐색한다. 이때 depth가 limit이면(즉 numbers의 크기이면), 그간의 결과값이 target 과 일치하는지 체크한다.