https://programmers.co.kr/learn/courses/30/lessons/43165
코딩테스트 연습 - 타겟 넘버
n개의 음이 아닌 정수가 있습니다. 이 수를 적절히 더하거나 빼서 타겟 넘버를 만들려고 합니다. 예를 들어 [1, 1, 1, 1, 1]로 숫자 3을 만들려면 다음 다섯 방법을 쓸 수 있습니다. -1+1+1+1+1 = 3 +1-1+1+1+
programmers.co.kr
문제 설명
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 이하인 자연수입니다.
입출력 예
number | target | return |
[1, 1, 1, 1, 1] | 3 | 5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
static int len; | |
static int answer; | |
static int t; | |
public int solution(int[] numbers, int target) { | |
answer = 0; | |
len = numbers.length; | |
t = target; | |
func(0, 0, numbers); | |
return answer; | |
} | |
static void func(int depth, int sum, int[] numbers) { | |
if (depth == len) { | |
if(sum == t) | |
answer++; | |
} else { | |
func(depth + 1, sum + numbers[depth], numbers); | |
func(depth + 1, sum - numbers[depth], numbers); | |
} | |
} | |
} |
일반적인 dfs를 활용한 백트래킹 문제이다.
더할 때와 뺄 때를 잘 나누어서 재귀함수를 호출해주면 된다.
'Algorithm > Programers' 카테고리의 다른 글
[Programers] 카드 짝 맞추기 (Kotlin) (2) | 2022.12.08 |
---|---|
[프로그래머스] 그래프 - 가장 먼 노드 (Java) (0) | 2021.08.02 |
[프로그래머스] 이분탐색 - 입국심사 (Java) (0) | 2021.05.25 |
[프로그래머스] 해시 - 베스트앨범 (0) | 2021.04.28 |
[프로그래머스] 해시 - 전화번호 목록 (Java) (0) | 2021.04.28 |
댓글