public IList <IList <int> > FourSum(int[] nums, int target) { //Array.Sort(nums); var hashSet = new HashSet <NumSet>(); var result = new List <IList <int> >(); for (int i = 0; i < nums.Length; i++) { var threeSum = ThreeSum(nums, target - nums[i], i); if (threeSum.Count > 0) { foreach (var threeruplet in threeSum) { threeruplet.Add(nums[i]); var set = new NumSet(threeruplet); if (!hashSet.Contains(set)) { hashSet.Add(set); result.Add(set.List); } } } } return(result); }
private List <List <int> > ThreeSum(int[] nums, int target, int ignoreIndex) { var result = new List <List <int> >(); var hashSet = new HashSet <NumSet>(); for (int i = 0; i < nums.Length; i++) { if (i == ignoreIndex) { continue; } var twoSum = TwoSum(nums, target - nums[i], i, ignoreIndex); if (twoSum.Count > 0) { foreach (var duplet in twoSum) { duplet.Add(nums[i]); var set = new NumSet(duplet); if (!hashSet.Contains(set)) { hashSet.Add(set); result.Add(set.List); } } } } return(result); }
private List <List <int> > TwoSum(int[] nums, int target, int ignoreIndex1, int ignoreIndex2) { var result = new List <List <int> >(); var hashSet = new HashSet <NumSet>(); var dict = new Dictionary <int, List <int> >(); for (int i = 0; i < nums.Length; i++) { if (i == ignoreIndex1 || i == ignoreIndex2) { continue; } if (dict.ContainsKey(nums[i])) { dict[nums[i]].Add(i); } else { dict.Add(nums[i], new List <int>() { i }); } } for (int i = 0; i < nums.Length; i++) { if (i == ignoreIndex1 || i == ignoreIndex2) { continue; } int key = target - nums[i]; if (dict.ContainsKey(key)) { foreach (int index in dict[key].Where(v => v != i)) { var set = new NumSet(new List <int>() { nums[i], nums[index] }); if (!hashSet.Contains(set)) { hashSet.Add(set); result.Add(set.List); } } } } return(result); }