List all combinations in a list of values
In C#, given a dynamic list of integers, it is often necessary to generate all possible combinations of its elements. For example, for the list {1, 2, 3}, you need to generate the following combination:
<code>{1, 2, 3} {1, 2} {1, 3} {2, 3} {1} {2} {3}</code>
To do this, use the following algorithm:
The C# code provided demonstrates the implementation of this algorithm:
<code class="language-csharp">static void Main(string[] args) { GetCombination(new List<int> { 1, 2, 3 }); } static void GetCombination(List<int> list) { double count = Math.Pow(2, list.Count); for (int i = 1; i < count; i++) { string binary = Convert.ToString(i, 2).PadLeft(list.Count, '0'); List<int> combination = new List<int>(); for (int j = 0; j < binary.Length; j++) { if (binary[j] == '1') { combination.Add(list[j]); } } Console.WriteLine(string.Join(", ", combination)); } }</code>
The above is the detailed content of How to Generate All Possible Combinations from a List of Integers in C#?. For more information, please follow other related articles on the PHP Chinese website!