2025-08-25 20:52:21 +09:00

29 lines
919 B
Swift

func dfs(_ n: Int, _ m: Int, _ nums: [Int], _ visited: inout [Bool], _ result: inout [Int]) {
if result.count == m {
print(result.map{String($0)}.joined(separator: " "))
return
}
var prev = -1
for i in 0..<n {
if !visited[i] && nums[i] != prev {
visited[i] = true
result.append(nums[i])
dfs(n,m,nums,&visited,&result)
_ = result.popLast()
visited[i] = false
prev = nums[i]
}
}
}
if let input1 = readLine(), let NM = input1.split(separator: " ").map({Int($0)}) as? [Int], NM.count == 2 {
let N = NM[0]
let M = NM[1]
if let input2 = readLine(), let nums = input2.split(separator: " ").map({Int($0)}) as? [Int], nums.count == N {
var visited:[Bool] = Array(repeating: false, count: N)
var result: [Int] = []
dfs(N, M, nums.sorted(), &visited, &result)
}
}