-
[프로그래머스/Level 2] 타겟 넘버 (C++)알고리즘 문제풀이/프로그래머스 2020. 11. 5. 16:23
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
전형적인 DFS 문제였습니다.
#include <string> #include <vector> using namespace std; int answer; void DFS(int L, int sum, vector<int> numbers, int target) { if(L == numbers.size()) { if(sum == target) answer++; return; } else { DFS(L + 1, sum - numbers[L], numbers, target); DFS(L + 1, sum + numbers[L], numbers, target); } } int solution(vector<int> numbers, int target) { DFS(0, 0, numbers, target); // DFS Level(인덱스), 합, 벡터, 타겟넘버 return answer; }
'알고리즘 문제풀이 > 프로그래머스' 카테고리의 다른 글
[프로그래머스/Level 2] 가장 큰 정사각형 찾기 (C++) (0) 2020.11.05 [프로그래머스/Level 2] 카펫 (C++) (0) 2020.11.05 [프로그래머스/Level 2] 구명보트 (C++) (0) 2020.11.05 [프로그래머스/Level 2] H-Index (C++) (0) 2020.11.04 [프로그래머스/Level 2] 더 맵게 (C++) (0) 2020.11.04