๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm

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

๋ฐ˜์‘ํ˜•

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

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

๋ฌธ์ œ ์ ‘๊ทผ

dfs๋ฅผ ์ด์šฉํ•ด์„œ numbers[0] ๋ถ€ํ„ฐ numbers[numbers.length-1]๊นŒ์ง€ ๋ชจ๋“  ์ˆซ์ œ์—๋Œ€ํ•ด์„œ +,-ํ•œ ๊ฒฝ์šฐ๋ฅผ ํƒ์ƒ‰ํ•ด์„œ target์ด ๋˜๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ตฌํ–ˆ๋‹ค.

Code

class Solution {
    int answer;
    int[] nums;
    public int solution(int[] numbers, int target) {
        answer = 0;
        nums = numbers;
        dfs(0, 0, target);
        return answer;
    }

    public void dfs(int num, int cnt, int target){
        if(cnt == nums.length){
            if(num == target){
              answer++;  
            }
            return;
        }
        else {
            dfs(num + nums[cnt], cnt+1, target);
            dfs(num - nums[cnt], cnt+1, target);
        }
    }
}

์–ด๋ ค์› ๋˜ ์  / ๋ฐฐ์šด ์  / ๋Š๋‚€ ์ 

๋ญ”๊ฐ€ dfs/bfs๋ฅผ ํ’€๋ฉด visited๋ฅผ ์‚ฌ์šฉํ•ด์•ผ๋งŒ ํ•  ๊ฒƒ ๊ฐ™์€ ๊ธฐ๋ถ„์ด๋ผ์„œ ๋ฌด์˜์‹์ ์œผ๋กœ ์„ ์–ธํ–ˆ๋Š”๋ฐ, ์ด ์นœ๊ตฌ๋Š” ์‚ฌ์šฉํ•  ํ•„์š”๊ฐ€ ์—†์—ˆ๋‹ค!

๋ฐ˜์‘ํ˜•