问题描述:给定一个数组A和一个数字n,要求在A中找出所有的可能组合,使得他们的和等于n,A中的数字可以重复使用
解题思路:可以从大往小找。将数组从大到小排序,对于每一个数x,如果它等于n,则返回;如果小于n,先加入列表中,计算n-x,然后从小于等于x的数中找出小于n-x的,将每个数加入到列表中,继续找下一个数;如果找不到这样的数,那么路径错误;如果到最后可以得到剩下的数等于0,说明这条路径可行。
public class Solution { public IList<IList<int>> CombinationSum(int[] candidates, int target) { List<IList<int>> lists=new List<IList<int>>(); if(candidates.Length==0) return lists; List<int> candicatesList = candidates.ToList(); candicatesList.Sort(); for (int i = candicatesList.Count - 1; i >= 0; i--) { if (candicatesList[i] == target) { List<int> candicate=new List<int>(){candicatesList[i]}; if(!lists.Contains(candicate,new Comparint())) lists.Add(candicate); } else if (candicatesList[i] < target) { GetCombination(candicatesList, new List<int>() { candicatesList[i] }, i, target, lists); } } for (int i = 0; i < lists.Count; i++) ((List<int>)lists[i]).Sort(); lists.Sort(new Comparint()); return lists; } public void GetCombination(List<int> sortedList, List<int> combinations,int k,int target,List<IList<int>> res ) { int left = target - sortedList[k]; if (left == 0) { combinations.Sort(); if (!res.Contains(combinations,new Comparint())) res.Add(combinations); } int[] array = new int[combinations.Count]; combinations.CopyTo(array); int index = Search(sortedList, k,left); if (index >= 0) { List<int> nums = GetUniqueItems(sortedList, index); for (int i = 0; i < nums.Count; i++) { List<int> list = array.ToList(); list.Add(nums[i]); GetCombination(sortedList,list, sortedList.IndexOf(nums[i]), left,res); } } } public int Search(List<int> sortedList,int bound, int n) { int val = -1; for (int i = 0; i <=bound; i++) { if (sortedList[i] <= n) val = i; else break; } if (val >= 0) return val; return -1; } public List<int> GetUniqueItems(List<int> sortedList, int index) { List<int> nums = new List<int>(); for (int i = 0; i <= index; i++) { if(!nums.Contains(sortedList[i])) nums.Add(sortedList[i]); } return nums; } class Comparint : IEqualityComparer<IList<int>>,IComparer<IList<int>> { public bool Equals(IList<int> x1, IList<int> x2) { if (x1.Count != x2.Count) return false; bool b = true; for (int i = 0; i < x1.Count; i++) { if (x1[i]!=x2[i]) { b = false; break; } } return b; } public int Compare(IList<int> x1, IList<int> x2) { int i=0; for (i = 0; i < Math.Min(x1.Count,x2.Count); i++) { if (x1[i] != x2[i]) { return x1[i] - x2[i]; } } return 0; } public int GetHashCode(IList<int> obj) { return obj.ToString().GetHashCode(); } } }