728x90
๐๋ฌธ์ ๋ณด๋ฌ๊ฐ๊ธฐ
๐จ๐ปํ์ด ๊ณผ์
DFS๋ก ํ ์ ์์ต๋๋ค. ๊น์ด๋ฅผ numbers์ ํฌ๊ธฐ๋งํผ ๋ด๋ ค ๊ฐ์ ๋, ์ด ๋๊น์ง์ ์ฐ์ฐ ๊ฒฐ๊ณผ์ target์ด ๊ฐ์ผ๋ฉด answer++ ํด์ฃผ๋ฉด ๋ฉ๋๋ค. ๋ํ๋ ๊ฒฝ์ฐ์ ๋นผ๋ ๊ฒฝ์ฐ ๋ ๊ฐ์ง๋ง ์์ผ๋ฏ๋ก 2๊ฐ๋ง ์ฌ๊ท๋ก ์์ฑํ๋ฉด ๋๊ฒ ๋ค์.
โ๏ธ์์ค ์ฝ๋ ๋ฐ ๊ฒฐ๊ณผ
#include <vector>
using namespace std;
void DFS(const vector<int>& numbers, const int& target, int sum, int idx, int& answer) {
if (idx == numbers.size()) {
if (sum == target)
answer++;
return;
}
DFS(numbers, target, sum + numbers[idx], idx + 1, answer);
DFS(numbers, target, sum - numbers[idx], idx + 1, answer);
}
int solution(vector<int> numbers, int target) {
int answer = 0;
DFS(numbers, target, 0, 0, answer);
return answer;
}
728x90
๋ฐ์ํ
'๐คAlgorithm > Programmers' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Programmers] Lv2. ๋ ๋งต๊ฒ | C++ (0) | 2023.06.21 |
---|---|
[Programmers] Lv2. k์ง์์์ ์์ ๊ฐ์ ๊ตฌํ๊ธฐ | C++ (0) | 2023.06.21 |
[Programmers] Lv2. ๋ด์ค ํด๋ฌ์คํฐ๋ง | C++ (0) | 2023.06.20 |
[Programmers] Lv2. ๊ธฐ๋ฅ๊ฐ๋ฐ | C++ (0) | 2023.06.16 |
[Programmers] Lv2. ์์ | C++ (0) | 2023.06.15 |