๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ’ปTech/โ˜•Java

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

by _viper_ 2023. 9. 25.
๋ฐ˜์‘ํ˜•

๐Ÿ“„ ๋ฌธ์ œ

ํƒ€๊ฒŸ ๋„˜๋ฒ„

 

๐Ÿ’ก ํ’€์ด

๊นŠ์ด ์šฐ์„  ํƒ์ƒ‰ (DFS)์„ ํ™œ์šฉํ•˜์—ฌ ์ฃผ์–ด์ง„ ์ˆซ์ž ๋ฐฐ์—ด์—์„œ ๊ฐ ์ˆซ์ž๋ฅผ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ ํŠน์ • ๋ชฉํ‘œ ์ˆซ์ž(target)๋ฅผ ๋งŒ๋“ค ์ˆ˜ ์žˆ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ๋ฐฉ์‹์ž…๋‹ˆ๋‹ค.

 

class Solution {

    private int answer = 0;

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

    private void dfs(int[] numbers, int target, int index, int currentSum) {
        if (index == numbers.length) {
            // ๋ฐฐ์—ด์˜ ๋๊นŒ์ง€ ๋„๋‹ฌํ•œ ๊ฒฝ์šฐ, ํ˜„์žฌ ํ•ฉ์ด ํƒ€๊ฒŸ๊ณผ ์ผ์น˜ํ•˜๋Š”์ง€ ํ™•์ธํ•˜๊ณ  answer๋ฅผ ์—…๋ฐ์ดํŠธ
            if (currentSum == target) {
                answer++;
            }
            return;
        }

        // ํ˜„์žฌ ์ˆซ์ž๋ฅผ ๋”ํ•˜๊ฑฐ๋‚˜ ๋นผ์„œ ๋ชจ๋“  ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ๋ฅผ ํƒ์ƒ‰
        dfs(numbers, target, index + 1, currentSum + numbers[index]);
        dfs(numbers, target, index + 1, currentSum - numbers[index]);
    }
}