a group numbers {1,2,5,10,20,50}, Choose up to 5 numbers to form a combination, use c#
- User
a group numbers {1,2,5,10,20,50}, Choose up to 5 numbers to form a combination, use c#
- Assistant
Here's an example code in C# that generates all possible combinations using up to 5 numbers from the given group:
using System; using System.Collections.Generic; class Program { static void Main(string[] args) { List<int> numbers = new List<int> { 1, 2, 5, 10, 20, 50 }; int maxLength = 5; List<List<int>> combinations = GenerateCombinations(numbers, maxLength); foreach (List<int> combination in combinations) { Console.WriteLine(string.Join(", ", combination)); } } static List<List<int>> GenerateCombinations(List<int> numbers, int maxLength) { List<List<int>> combinations = new List<List<int>>(); int n = numbers.Count; for (int size = 1; size <= maxLength; size++) { GenerateCombinationHelper(numbers, combinations, new List<int>(), size, n, 0); } return combinations; } static void GenerateCombinationHelper(List<int> numbers, List<List<int>> combinations, List<int> currentCombination, int size, int n, int index) { if (size == 0) { combinations.Add(new List<int>(currentCombination)); return; } for (int i = index; i < n; i++) { currentCombination.Add(numbers[i]); GenerateCombinationHelper(numbers, combinations, currentCombination, size - 1, n, i + 1); currentCombination.RemoveAt(currentCombination.Count - 1); } } }