Publish:

ํƒœ๊ทธ: , , , , ,

์นดํ…Œ๊ณ ๋ฆฌ:

img_3.png

๋ฌธ์ œ

๋ฌธ์ œ ๋งํฌ

img_3.png

์„ค๋ช…

numbers ๋ฐฐ์—ด์˜ ๊ฐ ํ•ญ๋ชฉ์„ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ๋Š” ๊ณผ์ • ์ค‘ target ์˜ ์ˆซ์ž์™€ ๊ฐ™์•„์ง€๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ.

ํ’€์ด

๋ฌธ์ œ ์ ‘๊ทผ ๋ฐฉํ–ฅ

  • ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ๋Š” ๋‘ ๊ฐ€์ง€ ์„ ํƒ์ง€๊ฐ€ ์žˆ๋‹ค.
  • ์ฒซ ๋ฒˆ์งธ ์ˆซ์ž๋ถ€ํ„ฐ ์‹œ์ž‘ํ•ด ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ๊ณ , ๊ทธ ๊ฒฐ๊ณผ๋ฅผ ๋‹ค์Œ ์ˆซ์ž์— ์ „๋‹ฌํ•˜๋Š” ์‹์œผ๋กœ ์žฌ๊ท€์ ์œผ๋กœ ์ ‘๊ทผํ•œ๋‹ค.
  • dfs ํ•จ์ˆ˜์—์„œ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ๋Š” ๊ฒฝ์šฐ์— ๋Œ€ํ•ด ์žฌ๊ท€ ํ˜ธ์ถœํ•œ๋‹ค.
  • ๊ธฐ์ € ์กฐ๊ฑด :
    • dfs ๋ฅผ numbers ๋ฐฐ์—ด ๊ธธ์ด ๋งŒํผ ํ˜ธ์ถœํ–ˆ์œผ๋ฉด ์ข…๋ฃŒ์‹œํ‚จ๋‹ค. (๋ชจ๋“  ํ•ญ๋ชฉ์„ ํƒ์ƒ‰ํ–ˆ๋‹ค๋Š” ์˜๋ฏธ)
    • sum ์ด target ๊ณผ ๊ฐ™์€ ๊ฒฝ์šฐ ์นด์šดํŠธ๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

dfs ๊ณผ์ •์„ ๋ช‡๊ฐ€์ง€ ๊ฒฝ์šฐ๋งŒ ๋Œ€๋žต์ ์œผ๋กœ ๊ทธ๋ ค๋ณด๋ฉด ์•„๋ž˜์™€ ๊ฐ™๋‹ค. dfs ๊ฐ€ ํ•œ๋ฒˆ ํ˜ธ์ถœ๋  ๋•Œ๋งˆ๋‹ค sum ์— ๋Œ€ํ•ด ๋”ํ•˜๋Š” ๊ฒฝ์šฐ์™€ ๋นผ๋Š” ๊ฒฝ์šฐ๋ฅผ ๋ชจ๋‘ ํƒ์ƒ‰ํ•œ๋‹ค. ๊ทธ ๊ณผ์ •์—์„œ sum ๊ณผ target ์ด ๊ฐ™์€ ๊ฒฝ์šฐ์—” answer ์˜ ๊ฐฏ์ˆ˜๋ฅผ ํ•˜๋‚˜์”ฉ ์ฆ๊ฐ€์‹œ์ผœ ์ค€๋‹ค. img_3.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
  static int answer = 0;

  public int solution(int[] numbers, int target) {
    answer = 0; // ํ˜ธ์ถœ ์‹œ answer ์ดˆ๊ธฐํ™”
    dfs(numbers, target, 0, 0);
    return answer;
  }

  private void dfs(int[] numbers, int target, int index, int sum) {
    if (index == numbers.length) { // index ์ฆ๊ฐ€ ์ œํ•œ ์กฐ๊ฑด
      if (sum == target) {  // ์นด์šดํŠธ ์กฐ๊ฑด
        answer++;
      }
      return;
    }
    dfs(numbers, target, index + 1, sum + numbers[index]);
    dfs(numbers, target, index + 1, sum - numbers[index]);
  }
}
๋ฐฉ๋ฌธํ•ด ์ฃผ์…”์„œ ๊ฐ์‚ฌํ•ฉ๋‹ˆ๋‹ค! ๋Œ“๊ธ€,์ง€์ ,ํ”ผ๋“œ๋ฐฑ ์–ธ์ œ๋‚˜ ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค๐Ÿ˜Š

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ