1. 문제
코딩테스트 연습 - 타겟 넘버
n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+
programmers.co.kr
2. 소스코드
- 매우 간단한 DFS문제
소스코드
#include <string>
#include <vector>
using namespace std;
int ans, t;
vector<int>copy_numbers;
void dfs(int sum, int depth){
if(depth >= copy_numbers.size()) {
if(sum == t) ans++;
return;
}
dfs(sum + copy_numbers[depth] ,depth + 1);
dfs(sum - copy_numbers[depth] ,depth + 1);
}
int solution(vector<int> numbers, int target) {
t = target;
copy_numbers = numbers;
dfs(0,0);
return ans;
}
'알고리즘 > 프로그래머스' 카테고리의 다른 글
[ 프로그래머스 / 완전탐색 ] 카펫 (0) | 2020.06.30 |
---|---|
[ 프로그래머스 / Map ] 위장 (0) | 2020.06.30 |
[ 프로그래머스 / 투포인트 ] 숫자의 표현 (0) | 2020.06.30 |
[ 프로그래머스 / DP ] 땅따먹기 (0) | 2020.06.30 |
[ 프로그래머스 / BFS ] 카카오 프렌즈 컬러링 북 (0) | 2020.06.30 |