SW Test/Programmers

[Programmers] Lv2. ํƒ€๊ฒŸ ๋„˜๋ฒ„(kotlin)

An effort will never betray ๐Ÿ˜Ž 2022. 8. 7. 23:54
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/43165?language=kotlin

 

 

์˜ˆ์‹œ

https://school.programmers.co.kr/learn/courses/30/lessons/43165?language=kotlin

 

 

ํ’€์ด

  • DFS ๊ธฐ๋ณธ์ ์ธ ๋ฌธ์ œ ์œ ํ˜•์œผ๋กœ ์žฌ๊ท€์˜ break point๋งŒ ์ž˜ ์ง€์ •ํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.
class Solution {
    var answer = 0
    
    fun getresult(numbers: IntArray, checks: IntArray, target: Int){
        if(checks.size == numbers.size){
            val sum = numbers.foldIndexed(0){index, acc, i ->
                acc + i*checks[index]
            }
            
            if(target == sum) answer++
        }else{
            getresult(numbers, checks + intArrayOf(-1), target)
            getresult(numbers, checks + intArrayOf(1), target)
        }
    }
    
    fun solution(numbers: IntArray, target: Int): Int {
        getresult(numbers, intArrayOf(), target)
        return answer
    }
}

 

 

 

์ฐธ๊ณ 

 

foldIndexed - Kotlin Programming Language

 

kotlinlang.org

 

๋ฐ˜์‘ํ˜•