문제 링크입니다: 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
간단한 DFS 문제였습니다.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <string> | |
#include <vector> | |
using namespace std; | |
int result; | |
void func(int idx, vector<int> &numbers, int target, int sum) | |
{ | |
if (idx == numbers.size()) | |
{ | |
if (target == sum) | |
{ | |
result++; | |
} | |
return; | |
} | |
func(idx + 1, numbers, target, sum + numbers[idx]); | |
func(idx + 1, numbers, target, sum - numbers[idx]); | |
} | |
int solution(vector<int> numbers, int target) { | |
func(0, numbers, target, 0); | |
return result; | |
} | |
int main(void) | |
{ | |
vector<int> numbers = { 1, 1, 1, 1, 1 }; | |
int target = 3; | |
cout << solution(numbers, target) << "\n"; | |
return 0; | |
} |

개발환경:Visual Studio 2017
지적, 조언, 질문 환영입니다! 댓글 남겨주세요~
반응형
'알고리즘 > programmers' 카테고리의 다른 글
[Programmers 코딩테스트 고득점 Kit] 단어 변환 (0) | 2021.09.10 |
---|---|
[Programmers 코딩테스트 고득점 Kit] 네트워크 (0) | 2021.09.08 |
[Programmers 위클리 챌린지 6주차] 복서 정렬하기 (0) | 2021.09.06 |
[Programmers 위클리 챌린지 5주차] 모음 사전 (0) | 2021.09.04 |
[Programmers 위클리 챌린지 4주차] 직업군 추천하기 (0) | 2021.09.04 |