How to get all subsets of an array?

前端 未结 12 2525
既然无缘
既然无缘 2020-11-27 17:54

Given an array: [dog, cat, mouse]

what is the most elegant way to create:

[,,]
[,,mouse]
[,cat,]
[,cat,mouse]
[dog,,]
[dog,,mouse]
[dog,         


        
12条回答
  •  孤街浪徒
    2020-11-27 18:16

    This is a small change to Mehrdad's solution above:

    static IEnumerable GetSubsets(T[] set) {
        bool[] state = new bool[set.Length+1];
        for (int x; !state[set.Length]; state[x] = true ) {
            yield return Enumerable.Range(0, state.Length)
                                   .Where(i => state[i])
                                   .Select(i => set[i])
                                   .ToArray();
            for (x = 0; state[x]; state[x++] = false);
        }
    }
    

    or with pointers

    static IEnumerable GetSubsets(T[] set) {
        bool[] state = new bool[set.Length+1];
        for (bool *x; !state[set.Length]; *x = true ) {
            yield return Enumerable.Range(0, state.Length)
                                   .Where(i => state[i])
                                   .Select(i => set[i])
                                   .ToArray();
            for (x = state; *x; *x++ = false);
        }
    }
    

提交回复
热议问题