【问题标题】:如何在给定的大小为 n 的数组中快速生成 r 元素的组合?
【发布时间】:2022-01-23 10:00:00
【问题描述】:

我想要总排列对及其计数 喜欢。 如果输入数组是 {1, 2, 3, 4} 并且 r 是 2。 那么输出应该是 {1, 2}, {1, 3}, {1, 4}, {2, 3}, {2, 4} 和 {3, 4}。

【问题讨论】:

  • 你尝试了什么?

标签: swift permutation


【解决方案1】:

实际上总排列对

[[1, 2], [1, 3], [1, 4], [2, 1], [2, 3], [2, 4], [3, 1], [3, 2], [3, 4], [4, 1], [4, 2], [4, 3]]

没有必要重新发明轮子。 Apple 提供了一系列有用且经过优化的算法。

将包 Swift Algorithms 添加到您的项目中

然后写

import Algorithms

let array = [1, 2, 3, 4]
    
let permutations = array.permutations(ofCount: 2)
print(Array(permutations), permutations.count)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    • 2015-12-18
    • 2021-12-06
    相关资源
    最近更新 更多