문제
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 answer = 0;
void dfs(vector<int> numbers, int target,int sum, int count){
if(count == numbers.size()){
if(sum == target) answer++;
return;
}
//dfs : -1의 부호, count --
dfs(numbers, target, sum + numbers[count],count+1);
//dfs : 1의 부호, count --
dfs(numbers, target, sum - numbers[count],count+1);
}
int solution(vector<int> numbers, int target) {
dfs(numbers, target,0,0);
return answer;
}
간단한 분할정복 dfs 문제이다.
근데 여기서 주의해야할 점은,
(1) void dfs는 되는데 int dfs()는 오류가 난다. return 0으로 처리를 해도 오류가 나는데, 이유를 모르겠다.
(2) recursion 함수 매개변수에 count ++ 가 아닌 count+1으로 작성
'programming language > Algorithm' 카테고리의 다른 글
[완전탐색 simulating 예제] 프로그래머스 완전탐색 level2 소수찾기 (0) | 2022.03.17 |
---|---|
[Divide and Conquer 예제] 프로그래머스 Level3 네트워크 (0) | 2021.08.25 |
Branch and Bound (0) | 2021.08.20 |
[Dynamic Programming 예제] 백준 12865 배낭문제 (0) | 2021.08.20 |
[Backtracking 예제] 백준 9663 N-Queens (0) | 2021.08.19 |