Using generator in Kotlin


  • 0
    J
    import kotlin.coroutines.experimental.buildSequence
    
    class Solution {
        fun permuteGenerator(nums: List<Int>): Sequence<List<Int>> = buildSequence {
            if (nums.isEmpty()) {
                yield(listOf())
            } else {
                nums.forEachIndexed { index, i -> permuteGenerator(nums.without(index)).forEach { list -> yield(list + i) } }
            }
        }
    
        private fun <T>List<T>.without(idx: Int): List<T> = (if (idx > 0) this.take(idx) else listOf()) + this.drop(idx + 1)
        fun permute(nums: IntArray): List<List<Int>> = permuteGenerator(nums.toList()).toList()
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.