我如何获得尊重顺序的集合的所有子集 [英] How can I get all subsets of a set that respect the order

查看:101
本文介绍了我如何获得尊重顺序的集合的所有子集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个C#示例,该示例将在尊重订单的同时为我提供集合的所有子集。

I'm looking for a C# example that will give me all subsets of a set while respecting the order.

例如,我有A,B,并且想要:

For example I have A,B and would like:

A
B
AB
BA

请注意,出于我的目的, AB!= BA

Please note that for my purpose AB != BA.

该解决方案对于任何输入类型均应通用:

The solution should be generic for any input type:

List<List<T>> GetSubsets<T>(List<T> originalSet)

我遇到了一些很好的解决方案AB == BA的操作(例如为字符串列表生成所有组合),但到目前为止,我还没有找到任何解决上述问题的方法。

I've come across some great solutions using bitwise manipulation for AB == BA (e.g Generate all combinations for a list of strings) but so far I have failed to find anything to solve what I described above.

任何提示/指针将不胜感激!

Any tips/pointers would be much appreciated!

推荐答案

GetPermutations()是参考。来自 https://stackoverflow.com/a/10630026/1287352

GetPermutations() is ref. from https://stackoverflow.com/a/10630026/1287352

public static List<List<T>> PermutationOf<T>(HashSet<T> set)
{
    var result = new List<List<T>>();
    for (var length = 1; length <= set.Count; length++)
    {
        result.AddRange(GetPermutations<T>(set, length).Select(i => i.ToList()));
    }
    return result;
}

private static IEnumerable<IEnumerable<T>> GetPermutations<T>(IEnumerable<T> list, int length)
{
    if (length == 1) return list.Select(t => new T[] { t });

    return GetPermutations(list, length - 1)
        .SelectMany(t => list.Where(e => !t.Contains(e)),
        (t1, t2) => t1.Concat(new T[] { t2 }));
}

用法:

PermutationOf(new HashSet<Guid>() { Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid() })
PermutationOf(new HashSet<String>() { "A", "B", "C" })

结果:

A
B
C
A, B
A, C
B, A
B, C
C, A
C, B
A, B, C
A, C, B
B, A, C
B, C, A
C, A, B
C, B, A

这篇关于我如何获得尊重顺序的集合的所有子集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆