Getting all possible combinations from a list of numbers

前端 未结 3 2073
醉话见心
醉话见心 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 CreateSubsets(T[] originalArray) 
    { 
        List subsets = new List(); 
    
        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.

提交回复
热议问题