문제 : 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
오랜만에 카페와서 백준 풀려고했더니 노트북에서 비주얼스튜디오가 자꾸 튕긴다 ,, ㅠ ㅠ
그래서 오늘은 웹에서 바로 푸는 프로그래머스를 풀었다 :<
이 문제는 쌩 for문으로도 풀 수 있지만 DFS로 풀면 더 빠르고 간단하게 풀 수 있다.
사실 나도 전에 풀었던 코드 참고해서 풀 긴 했지만 하하
#include <string>
#include <vector>
using namespace std;
int cnt = 0;
void DFS(int idx, vector<int>& numbers, int sum, int target)
{
if (idx >= numbers.size())
{
if(sum == target)
{
cnt++;
}
return;
}
DFS(idx+1, numbers, sum+numbers[idx], target);
DFS(idx+1, numbers, sum-numbers[idx], target);
}
int solution(vector<int> numbers, int target) {
int answer = 0;
DFS(1, numbers, +numbers[0], target);
DFS(1, numbers, -numbers[0], target);
answer = cnt;
return answer;
}
'알고리즘 > DBS와BFS' 카테고리의 다른 글
[백준/C++] 2667번 단지번호붙이기 - BFS (0) | 2022.01.24 |
---|---|
[프로그래머스/C++] 네트워크 (BFS/DFS) (0) | 2022.01.18 |
[백준/C++] 2606번 바이러스 - DFS (0) | 2022.01.14 |
[백준/C++] 2606번 바이러스 - BFS (0) | 2022.01.13 |
[백준/C++] 2178번 미로 탐색 (0) | 2022.01.12 |