
-Code
class Solution {
static int answer = 0;
public int solution(int[] numbers, int target) {
backtracking(0, 0, numbers, target);
return answer;
}
private static void backtracking(int idx, int nowNum, int[] nums, int target) {
int length = nums.length;
if (idx == length) {
if (nowNum == target) {
answer++;
}
return;
}
backtracking(idx + 1, nowNum - nums[idx], nums, target);
backtracking(idx + 1, nowNum + nums[idx], nums, target);
}
}
처음에 if로 탈줄하는 문장을 2개로 나누어서 사용해서 틀렸었습니다. 위와 같이 length와 idx가 같을때 target과 같으면 answer++을 하고 반환하여 해결했습니다.
하지만 static을 사용해서 한게 조금 걸려서 재귀로 하는 방법도 찾아서 아래와 같이 타이핑 해봤습니다.
class Solution {
public int solution(int[] numbers, int target) {
return backtracking(0, 0, numbers, target);
}
private static int backtracking(int idx, int nowNum, int[] nums, int target) {
int length = nums.length;
// 현재 인덱스가 길이와 같을때, target과 같으면 1 아니면 0 반환
if (idx == length) {
return nowNum == target ? 1 : 0;
}
// 반환한 값들을 재귀를 통해 계속 더하면서 총 갯수 반환
return backtracking(idx + 1, nowNum - nums[idx], nums, target) +
backtracking(idx + 1, nowNum + nums[idx], nums, target);
}
}'Beakjoon&프로그래머스 > Java' 카테고리의 다른 글
| [프로그래머스/Java] 구명보트 (0) | 2026.01.02 |
|---|---|
| [백준/Java] 20733번 Triple Texting (0) | 2026.01.02 |
| [LeetCode/Java] Max Number of K-Sum Pairs (0) | 2026.01.01 |
| [LeetCode/Java] Container With Most Water (0) | 2026.01.01 |
| [프로그래머스/Java] n^2 배열 자르기 (0) | 2026.01.01 |