상세 컨텐츠

본문 제목

Baekjoon(Kotlin) - 15649. N과 M (1)

Problems(Kotlin)/Baekjoon

by KDLiam 2023. 9. 3. 14:04

본문

URL : https://www.acmicpc.net/problem/15649

 

15649번: N과 M (1)

한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. 수열은 사전 순으로 증가하는 순서로 출력해

www.acmicpc.net

 

[ RESULT ]

val br = System.`in`.bufferedReader()
val bw = System.`out`.bufferedWriter()

fun main() {

    val (N, M) = br.readLine().split(" ").map { it.toInt() }

    val arr = Array(N) { it + 1 }

    permutation(arr, N, M).forEach {
        bw.write(it.joinToString(" ") + "\n")
    }

    br.close()
    bw.close()
}

fun <T> permutation(Arr: Array<T>, N: Int, R: Int): List<List<T>> {
    val nArray = Arr.sliceArray(0 until R)
    val visited = BooleanArray(N)
    val list = mutableListOf<List<T>>()

    fun recursionPermutation(depth: Int = 0) {
        if (depth == R) {
            list.add(nArray.toList())
            return
        }

        Arr.forEachIndexed { index, t ->
            if(!visited[index]) {
                visited[index] = true
                nArray[depth] = t
                recursionPermutation(depth + 1)
                visited[index] = false
            }
        }
    }

    recursionPermutation()
    return list
}

 

 

BackTracking : 모든 경우의 수를 확인하는 것을 말함

 

효율적인 순열 코드를 구상하던 중 발견한 블로그

https://gyeong-log.tistory.com/51

 

[코틀린] 조합, 순열 구현하기

백트래킹을 공부하면서, 백트래킹 대표 입문 문제인 N과 M을 풀어보았다. Python으로 조합과 순열을 사용할 때가 나오면, 이미 구현된 라이브러리를 사용했었다. 그럼 Kotlin에서는 조합, 순열을 사

gyeong-log.tistory.com

관련글 더보기