Getting all possible combinations from a list of numbers

前端 未结 3 2056
醉话见心
醉话见心 2020-11-27 18:43

I\'m looking for an efficient way to achieve this:

  • you have a list of numbers 1.....n (typically: 1..5 or 1..7 or so - reasonably small, but can vary from c

相关标签:
3条回答
  • 2020-11-27 18:59

    This is something I have written in the past to accomplish such a task.

    List<T[]> CreateSubsets<T>(T[] originalArray) 
    { 
        List<T[]> subsets = new List<T[]>(); 
    
        for (int i = 0; i < originalArray.Length; i++) 
        { 
            int subsetCount = subsets.Count; 
            subsets.Add(new T[] { originalArray[i] }); 
    
            for (int j = 0; j < subsetCount; j++) 
            { 
                T[] newSubset = new T[subsets[j].Length + 1]; 
                subsets[j].CopyTo(newSubset, 0); 
                newSubset[newSubset.Length - 1] = originalArray[i]; 
                subsets.Add(newSubset); 
            } 
        } 
    
        return subsets; 
    }
    

    It's generic, so it will work for ints, longs, strings, Foos, etc.

    0 讨论(0)
  • 2020-11-27 19:01

    Not my code, but you're looking for the powerset. Google gave me this solution, which seems t work:

    public IEnumerable<IEnumerable<T>> GetPowerSet<T>(List<T> list)
    {
        return from m in Enumerable.Range(0, 1 << list.Count)
                  select
                      from i in Enumerable.Range(0, list.Count)
                      where (m & (1 << i)) != 0
                      select list[i];
    }
    

    Source: http://rosettacode.org/wiki/Power_set#C.23

    0 讨论(0)
  • 2020-11-27 19:11

    Just increment a binary number and take the elements corresponding to bits that are set.

    For instance, 00101101 would mean take the elements at indexes 0, 2, 3, and 5. Since your list is simply 1..n, the element is simply the index + 1.

    This will generate in-order permutations. In other words, only {1, 2, 3} will be generated. Not {1, 3, 2} or {2, 1, 3} or {2, 3, 1}, etc.

    0 讨论(0)
提交回复
热议问题