【问题标题】:Find all "pairing sets", such that all elements have a pair, and no pairs contain common elements查找所有“配对集”,使得所有元素都有一个配对,并且没有配对包含公共元素
【发布时间】:2021-09-16 15:11:21
【问题描述】:

我目前正在尝试解决以下问题。

我必须找到一个集合的所有对(具有偶数个元素),这样:

  1. 没有两对有共同的元素
  2. 所有元素都成对

举个例子:

pairingsSet({0, 1, 2, 3})
should return something like
{
    {{0, 1}, {2, 3}},
    {{0, 2}, {1, 3}},
    {{0, 3}, {1, 2}},
}

还有一个更详细的例子:

pairingsSet({0, 1, 2, 3, 4, 5})
should return something like
{
    {{0, 1}, {2, 3}, {4, 5}},
    {{0, 1}, {2, 4}, {3, 5}},
    {{0, 1}, {2, 5}, {3, 4}},
    {{0, 2}, {1, 3}, {4, 5}},
    {{0, 2}, {1, 4}, {3, 5}},
    ...
    {{0, 5}, {1, 3}, {2, 4}},
    {{0, 5}, {1, 4}, {2, 3}},
}

我知道解决这个问题的最简单方法是使用递归,但我不知道该怎么做。

我订购了上面的套装,因为它帮助我想出了一个解决方案,但顺序并不重要。我仍然不能完全确定解决方案。我可能很快就会找到答案,我提出这个问题以防其他人遇到类似问题。如果有人想出一个替代答案,我很乐意看到它!

(我目前正在研究Go 的解决方案,尽管非常欢迎使用其他语言的解决方案)

【问题讨论】:

    标签: language-agnostic set-theory


    【解决方案1】:

    这是我在Go 中的解决方案:

    func allPairingSetsForAlphabet(alphabet []int) [][][2]int {
        if len(alphabet) == 2 {
            return [][][2]int{{{alphabet[0], alphabet[1]}}}
        }
    
        first := alphabet[0]
        rest := alphabet[1:]
        var pairingsSet [][][2]int
        for i, v := range rest {
            pair := [2]int{first, v}
            withoutV := make([]int, len(rest)-1)
            copy(withoutV[:i], rest[:i])
            copy(withoutV[i:], rest[i+1:])
    
            // recursive call
            otherPairingsSet := allPairingSetsForAlphabet(withoutV)
            for _, otherPairings := range otherPairingsSet {
                thisPairing := make([][2]int, len(otherPairings)+1)
                thisPairing[0] = pair
                copy(thisPairing[1:], otherPairings)
                pairingsSet = append(pairingsSet, thisPairing)
            }
        }
        return pairingsSet
    }
    

    基本上它执行以下步骤:

    1. 如果字母表中只剩下两个东西,我们返回一个只包含这两个对的配对集(即{{{0, 1}}}
    2. 选择一个元素(我们称之为first
    3. 创建一个包含所有字母表元素的新集合,不包含first(我们将其称为rest
    4. 对于rest 中的每个元素 (v),我们:
      1. 制作一对{first, v}(我们称之为pair
      2. 创建rest 的子集,其中包含rest 中除v 之外的所有元素(我们将其称为withoutV
      3. 我们进行递归调用,allPairingsForAlphabet(withoutV)
      4. 对于此调用返回的每个配对 (pairing),我们将 {pair} U pairing 添加到结果中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-03
      • 2015-12-20
      • 2019-02-18
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-15
      相关资源
      最近更新 更多