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

HaJingJingยท2021๋…„ 6์›” 14์ผ
0

Algorithm

๋ชฉ๋ก ๋ณด๊ธฐ
64/119

0. ๋ฌธ์ œ

n๊ฐœ์˜ ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค. ์ด ์ˆ˜๋ฅผ ์ ์ ˆํžˆ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ ํƒ€๊ฒŸ ๋„˜๋ฒ„๋ฅผ ๋งŒ๋“ค๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด [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
์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์ˆซ์ž๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด numbers, ํƒ€๊ฒŸ ๋„˜๋ฒ„ target์ด ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ ์ˆซ์ž๋ฅผ ์ ์ ˆํžˆ ๋”ํ•˜๊ณ  ๋นผ์„œ ํƒ€๊ฒŸ ๋„˜๋ฒ„๋ฅผ ๋งŒ๋“œ๋Š” ๋ฐฉ๋ฒ•์˜ ์ˆ˜๋ฅผ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.

์ œํ•œ์‚ฌํ•ญ
์ฃผ์–ด์ง€๋Š” ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๋Š” 2๊ฐœ ์ด์ƒ 20๊ฐœ ์ดํ•˜์ž…๋‹ˆ๋‹ค.
๊ฐ ์ˆซ์ž๋Š” 1 ์ด์ƒ 50 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.
ํƒ€๊ฒŸ ๋„˜๋ฒ„๋Š” 1 ์ด์ƒ 1000 ์ดํ•˜์ธ ์ž์—ฐ์ˆ˜์ž…๋‹ˆ๋‹ค.

1. ์•„์ด๋””์–ด

๐Ÿ’ก DFS
๐Ÿ’ก ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๋กœ ๋‚˜๋ˆ„์–ด์„œ numbers๋ฅผ ๋”ํ•  ๋•Œ, ๋บ„ ๋•Œ ๋ชจ๋‘ ๊ณ ๋ คํ•จ
๐Ÿ’ก numbers๋ฅผ ๋ชจ๋‘ ๋‹ค ์“ฐ๊ณ  target number๋ž‘ ์ผ์น˜ํ•  ์‹œ์— count์— 1์„ ๋”ํ•ด์คŒ

2. ํ•ต์‹ฌ ํ’€์ด

1) ๋‘ ๊ฐ€์ง€ ๊ฒฝ์šฐ๋กœ ๋‚˜๋ˆ„์–ด์„œ numbers๋ฅผ ๋”ํ•  ๋•Œ, ๋บ„ ๋•Œ ๋ชจ๋‘ ๊ณ ๋ คํ•จ

dfs(numbers, target, depth+1, ret+numbers[depth]);
dfs(numbers, target, depth+1, ret-numbers[depth]);

2) numbers๋ฅผ ๋ชจ๋‘ ๋‹ค ์“ฐ๊ณ  target number๋ž‘ ์ผ์น˜ํ•  ์‹œ์— count์— 1์„ ๋”ํ•ด์คŒ

if(depth == numbers.length){
            if(ret == target)
                count++;
            return;
}

3. ์ฝ”๋“œ

class Solution {
    static int count = 0;
    public int solution(int[] numbers, int target) {
        int answer = 0;
        dfs(numbers, target, 0, 0);
        return answer = count;
    }
    
    public void dfs(int[] numbers, int target, int depth, int ret){
        if(depth == numbers.length){
            if(ret == target)
                count++;
            return;
        } else {
            dfs(numbers, target, depth+1, ret+numbers[depth]);
            dfs(numbers, target, depth+1, ret-numbers[depth]);
        }
    }
}

4. ๊ฒฐ๊ณผ

์„ฑ๊ณตโœจ

profile
๐ŸŒฑ์ดˆ๋ณด ๊ฐœ๋ฐœ์ž๐ŸŒฑ

0๊ฐœ์˜ ๋Œ“๊ธ€