n개의 음이 아닌 정수들이 있습니다. 이 정수들을 순서를 바꾸지 않고 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다.
-1+1+1+1+1 = 3
+1-1+1+1+1 = 3
+1+1-1+1+1 = 3
+1+1+1-1+1 = 3
+1+1+1+1-1 = 3
사용할 수 있는 숫자가 담긴 배열 numbers, 타겟 넘버 target이 매개변수로 주어질 때 숫자를 적절히 더하고 빼서 타겟 넘버를 만드는 방법의 수를 return 하도록 solution 함수를 작성해주세요.
접근 point
- bfs/dfs 알고리즘
Index 0 부터 시작하여 Index가 '배열 사이즈 - 1'을 도달 할 때 까지 + 혹은 - 로 계산하여, target number가 될 경우 count를 올려주는 방식이다.
#include <bits/stdc++.h>
using namespace std;
int cnt = 0; // target count 용도
void dfs(vector<int> numbers, int target, int idx, int sum) {
if(idx == numbers.size()-1) { // 배열의 마지막 index 도달
if(sum == target) cnt++; // target이 되었을 때 cnt 올리기
return;
}
dfs(numbers, target, idx+1, sum+numbers[idx+1]);
dfs(numbers, target, idx+1, sum-numbers[idx+1]);
}
int solution(vector<int> numbers, int target) {
dfs(numbers, target, 0, numbers[0]);
dfs(numbers, target, 0, -numbers[0]);
return cnt;
}
'프로그래머스' 카테고리의 다른 글
프로그래머스 lvl 2. N개의 최소공배수 [C++] (0) | 2023.08.31 |
---|---|
프로그래머스 lvl 2. 의상 [C++] (0) | 2023.08.17 |
프로그래머스 lvl 2. 영어 끝말잇기 [C++] (0) | 2023.07.07 |
프로그래머스 lvl 2. 귤 고르기 [C++] (0) | 2023.07.05 |
프로그래머스 lvl 2. 더 맵게 [C++] (0) | 2023.07.04 |