프로그래머스 - kotlin/LEVEL 2
타겟 넘버
배준형
2022. 12. 8. 00:07
문제 출처: https://school.programmers.co.kr/learn/courses/30/lessons/92341?language=kotlin
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제
나의 풀이
매우 간단한 dfs 문제이다. 숫자가 담긴 배열을 cnt가 numbers.size가 될때까지 '+' 와 '-'로 나눠서 dfs를 반복 해주면 된다.
class Solution {
var size = 0
fun solution(numbers: IntArray, target: Int): Int {
return dfs(0, 0, numbers, target)
}
var count = 0
fun dfs(cnt: Int, result: Int, numbers: IntArray, target: Int): Int {
if (cnt == numbers.size) {
if (result == target) count++
}
else {
dfs(cnt + 1, result + numbers[cnt], numbers, target)
dfs(cnt + 1, result - numbers[cnt], numbers, target)
}
return count
}
}