알고리즘

[프로그래머스] 타겟 넘버 - JAVA 풀이

sppl24 2024. 11. 12. 23:51
반응형

타겟 넘버

문제설명

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

제한사항

  • 주어지는 숫자의 개수는 2개 이상 20개 이하입니다.
  • 각 숫자는 1 이상 50 이하인 자연수입니다.
  • 타겟 넘버는 1 이상 1000 이하인 자연수입니다.

입출력 예


아이디어

  • 부분집합? -> 전형적인 DFS 연습문제다
  • 결과값을 잘 체크하면서 계산해 나가자

JAVA 풀이

class Solution {
    static int cnt = 0;
    public int solution(int[] numbers, int target) {
        recur(numbers, 0, target, 0);
        int answer = cnt;
        return answer;
    }
    public void recur(int[] numbers, int depth, int target, int res) {
        if (depth == numbers.length) {
            if (target == res) cnt++;
            return;
        } else {
            recur(numbers, depth + 1, target, res + numbers[depth]);
            recur(numbers, depth + 1, target, res - numbers[depth]);
        }
    }
}
반응형