using System.Collections.Generic;
public static void Main()
Console.WriteLine("******** ThreeSum ********");
var result = ThreeSum(new int[] {-1, 0, 1, 2, -1, -4}, 0);
Console.WriteLine("\n******** ThreeSumWithDup ********");
result = ThreeSumWithDup(new int[] {-1, 0, 1, 2, -1, -4}, 0);
private static List<List<int>> ThreeSum(int[] nums, int target)
var result = new List<List<int>>();
for(int i = 0; i < nums.Length - 2; i++)
if(i == 0 || (i > 0 && nums[i] != nums[i - 1]))
int newTarget = target - nums[i];
int high = nums.Length - 1;
if(nums[low] + nums[high] == newTarget)
var list = new List<int>(){nums[i], nums[low], nums[high]};
while(low < high && nums[low] == nums[low + 1])
while(low < high && nums[high] == nums[high - 1])
else if(nums[low] + nums[high] > newTarget)
private static List<List<int>> ThreeSumWithDup(int[] nums, int target)
List<List<int>> result = new List<List<int>>();
for(int i = 0; i < nums.Length - 2; i++)
var twoSum = TwoSum(nums, target - nums[i], i);
var list = new List<int>();
private static int[] TwoSum(int[] nums, int target, int current)
var cache = new Dictionary<int, int>();
for(int i = 0; i < nums.Length; i++)
if(!cache.ContainsKey(target - nums[i]))
return new int[] {target - nums[i], nums[i]};
private static void Print(List<List<int>> result)
foreach(var list in result)
Console.WriteLine(string.Join(",", list.ToArray()));