/// /// Find all sub number groups that sum equal to a given number /// /// sorted list /// total number /// all sub number groups private static IEnumerable > FindCombination(List list, int total) { var found = new List >(); //[2,3,4] total:1 if (list.First() > total) return found; //[2] total:1 if (list.Count == 1 && list.First() != total) return found; //[1,2, 6] => [1,2] if (list.Contains(total)) { found.Add(new List { total }); list.Remove(total); } //[1,2,3] => 1+2+3 =6 if (list.Sum() == total) { found.Add(list); return found; } //travel every item to find combination for (var i = 0; i < list.Count; i++) { var seed = list[i]; var subTotal = total - seed; var clonedList = new List (list); clonedList.RemoveAt(i); var combinations = FindCombination(clonedList, subTotal); foreach (var item in combinations) { item.Add(seed); item.Sort(); if (!IsContainArray(found, item)) found.Add(item); } } return found; } /// /// To check if an list of list contains a list /// /// /// /// contains or not private static bool IsContainArray(IEnumerable > list, IEnumerable item) { return list.Select(l => string.Join(",", l)).Contains(string.Join(",", item)); }
这个算法可以说是纯为实现而实现,没有经过任何精巧设计,但从测试结果来看,还没找到漏掉的。