๋ฌธ์
https://school.programmers.co.kr/learn/courses/30/lessons/43165
ํ์ด
๐ก DFS, ์ฌ๊ทํจ์
- ์ข ๋ฃ ์กฐ๊ฑด: numbers ๋ฐฐ์ด์ ๋ชจ๋ ์๋ฅผ ์ ํ ์๋ฃ
- ๋ค์ ์ธ๋ฑ์ค๋ก ๋์ด๊ฐ๋ฉด์ + ๋๋ - ๋ฅผ ์ ํํ์ฌ ์ฐ์ฐํ ๊ฐ์ ๋๊ธด๋ค.
์ฝ๋
#include <iostream>
#include <vector>
using namespace std;
int answer;
void dfs(int idx, int sum, int target, vector<int> &numbers) {
if (idx == numbers.size()) { // ์ข
๋ฃ ์กฐ๊ฑด: ๋ชจ๋ ์ ํ์ ์๋ฃ
if (sum == target) { // target๊ณผ ๊ฐ์ผ๋ฉด ๊ฒฝ์ฐ์ ์ + 1
answer++;
}
return;
}
dfs(idx + 1, sum + numbers[idx], target, numbers); // + ์ ํ
dfs(idx + 1, sum - numbers[idx], target, numbers); // - ์ ํ
}
int solution(vector<int> numbers, int target) {
answer = 0;
dfs(0, 0, target, numbers);
return answer;
}
'๐ญ Problem Solving' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค][C++] ๋คํธ์ํฌ (0) | 2024.06.04 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค][C++] ํฐ ์ ๋ง๋ค๊ธฐ (0) | 2024.06.02 |
[ํ๋ก๊ทธ๋๋จธ์ค][C++] ์คํฌํธ๋ฆฌ (0) | 2024.05.31 |
[ํ๋ก๊ทธ๋๋จธ์ค][C++] ํคํจ๋ ๋๋ฅด๊ธฐ (0) | 2024.05.27 |
[BOJ][C++] ๋ฐฑ์ค 20546๋ฒ: ๐ ๊ธฐ์ ์ ๋งค๋งค๋ฒ ๐ (0) | 2024.05.26 |