๐Ÿ“ Coding Test Study/Algorithm Problem

[C++][Programmers][DFS/BFS] ํƒ€๊ฒŸ๋„˜๋ฒ„

ibelieveinme 2023. 5. 2. 23:40
728x90

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

 

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

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

programmers.co.kr

 

[๋ฌธ์ œํ’€์ด]

์ •์ˆ˜๋“ค์„ ์ˆœ์„œ๋ฅผ ๋ฐ”๊พธ์ง€ ์•Š๊ณ  ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ ํƒ€๊ฒŸ ๋„˜๋ฒ„๋ฅผ ๋งŒ๋“ค๋ฉด ๋œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค์–ด 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

 

๋‚˜๋Š” ํŠธ๋ฆฌ์—์„œ +, - ๊ฐ€์ง€๋ฅผ ์ณ๊ฐ€๋ฉฐ ๋ฐฉ๋ฒ•์„ ์ฐพ์•˜๋‹ค. 

index 0๋ฒˆ ๋ถ€ํ„ฐ 5๊นŒ์ง€ ๊ฐ€๋ฉฐ target number 3์ด ๋˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ์„ ๋•Œ๋งˆ๋‹ค answer ๋ฅผ +1 ์”ฉ ํ•ด์ค€๋‹ค.

์ด๋•Œ ๋Œ์•„์™€์„œ ๋‹ค๋ฅธ ๊ฒฝ๋กœ๋กœ ํƒ์ƒ‰ํ•ด์•ผ ํ•˜๋ฏ€๋กœ ํ•œ๋ฒˆ์€ +1๋กœ ํ•œ๋ฒˆ์€ -1๋กœ DFS ํƒ์ƒ‰์„ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

์ข…๋ฃŒ์กฐ๊ฑด์€ index๊ฐ’์ด numbers ๋ฒกํ„ฐ size์™€ ๊ฐ™์„ ๋•Œ์ด๊ณ  ์ด๋•Œ sum๊ฐ’๊ณผ target number์˜ ๊ฐ’์ด ์ผ์น˜ํ•˜๋Š”์ง€ ํŒ๋‹จํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

 

[์•Œ์•„๋‘˜ ๊ฒƒ]

๋Œ์•„์™€์„œ ๋‹ค๋ฅธ ๊ฒฝ๋กœ๋กœ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•์„ ์ฝ”๋“œ๋กœ ์งœ๋Š” ๋ฒ•

DFS(numbers, target, sum + numbers[index], index + 1);
DFS(numbers, target, sum - numbers[index], index + 1);

์ด๋ ‡๊ฒŒ ์žฌ๊ท€ํ•จ์ˆ˜ return ํ›„ ๋ฐ”๋กœ ๋‹ค์Œ์ค„์—์„œ ๋‹ค๋ฅธ ๊ฒฝ๋กœ๋กœ ํƒ์ƒ‰ํ•˜๋ฉด ๋œ๋‹ค.

์ด๋Ÿฐ ๋ฌธ์ œ๊ฐ€ ์€๊ทผ ๋งŽ์œผ๋‹ˆ ๊ธฐ์–ตํ•ด๋‘์ž.

 

[์ฝ”๋“œ]

#include <string>
#include <vector>
using namespace std;

int answer = 0;

void DFS(vector<int> numbers, int target, int sum, int index){
    if(index == numbers.size()) {
        if(sum == target) answer++;
        return;
    }
    DFS(numbers, target, sum + numbers[index], index + 1);
    DFS(numbers, target, sum - numbers[index], index + 1);    
}

int solution(vector<int> numbers, int target) {
    DFS(numbers, target, 0, 0);
       
    return answer;
}
728x90