https://programmers.co.kr/learn/courses/30/lessons/43165
코딩테스트 연습 - 타겟 넘버
n개의 음이 아닌 정수들이 있습니다. 이 정수들을 순서를 바꾸지 않고 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수
programmers.co.kr
재귀를 통한 DFS방법으로 문제를 풀어보았다.
#include <string>
#include <vector>
using namespace std;
int answer = 0;
void dfs(vector<int> numbers, int taget,int sum, int cnt) {
if(cnt==numbers.size()) {
if(taget == sum) answer++;
return;
}
dfs(numbers, taget, sum+numbers[cnt], cnt+1);
dfs(numbers, taget, sum-numbers[cnt], cnt+1);
}
int solution(vector<int> numbers, int target) {
int cnt = 0;
dfs(numbers, target,0, 0);
return answer;
}
'CodingTest Practice > Programmers' 카테고리의 다른 글
프로그래머스 : 네트워크(C++, Lv.3, DFS) (0) | 2022.05.18 |
---|---|
프로그래머스 : 더 맵게(C++, Lv.2, 힙) (0) | 2022.05.12 |
프로그래머스 : 숫자 문자열과 영단어 (C++, Lv.1) (0) | 2021.12.30 |
프로그래머스 : 없는 숫자 더하기 (C++, Lv.1) (0) | 2021.12.30 |
프로그래머스 : 신규 아이디 추천 (C++, Lv.1) (0) | 2021.12.30 |