[LeetCode] 216. Combination Sum III(Kotlin)

0

LeetCode

목록 보기
17/58
post-thumbnail
post-custom-banner

[LeetCode] 216. Combination Sum III(Kotlin)

풀이

class Solution {
    private val answer: MutableList<List<Int>> = mutableListOf()
    private var _k = -1
    private var _n = -1

    fun combinationSum3(k: Int, n: Int): List<List<Int>> {
        _k = k
        _n = n

        getCombination(1, listOf())
        return answer.toList()   
    }

    private fun getCombination(curNum:Int, combination:List<Int>){
        val comSum = combination.sum()
        val comSize = combination.size
    
        if((comSum > _n)||(comSize > _k)) return
        if(comSize == _k){
            if(comSum == _n) answer.add(combination)
            return
        }
        
        if(curNum >= 10) return
        // dont add curNum to combination
        getCombination(curNum+1, combination)
        // add curNum to combination
        getCombination(curNum+1, combination + listOf(curNum))
    }
}
profile
Be able to be vulnerable, in search of truth
post-custom-banner

0개의 댓글