๐Ÿ’ญ Problem Solving

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค][C++] ํƒ€๊ฒŸ ๋„˜๋ฒ„

0=2. 2024. 5. 31. 23:49

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/43165

 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

๐Ÿ’ก 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;
}