public List<int> OneSum(int[] nums,int target)
{
Array.Sort(nums);
List<int> map = new List<int>();
for(int i =0;i < nums.Length;i++)
{
if(nums[i]== target)
{
map.Add(nums[i]);
}else if(nums[i]> target)
{
break;
}
}
return map;
}
public List<List<int>> TwoSum(int[] nums, int target)
{
Array.Sort(nums);
List<List<int>> res = new List<List<int>>();
List<int> curlist = new List<int>();
for (int i = 0; i < nums.Length; i++)
{
int hi = nums.Length - 1;
while(i< hi)
{
if(nums[i]+ nums[hi] == target)
{
res.Add(new List<int> { nums[i], nums[hi] });
hi--;
}
else if(nums[i] + nums[hi] > target)
{
hi--;
}else if( nums[i] + nums[hi] < target)
{
break;
}
}
}
return res;
}
public IList<IList<int>> ThreeSum(int[] nums, int target)
{
//排序
Array.Sort(nums);
var res = new List<IList<int>>();
//当前元素向后匹配2个元素,所以最后2个元素不用被遍历
for (int i = 0; i < nums.Length - 2; i++)
{
if (i == 0 || (i > 0 && nums[i] != nums[i - 1]))
{
int lo = i + 1, hi = nums.Length - 1, sum = target - nums[i];
while (lo < hi)
{
//找到满足条件元素,添加到返回结果队列
if (nums[lo] + nums[hi] == sum)
{
res.Add(new List<int> { nums[i], nums[lo], nums[hi] });
//防止重复元素
while (lo < hi && nums[lo] == nums[lo + 1]) lo++;
while (lo < hi && nums[hi] == nums[hi - 1]) hi--;
//夹逼查找
lo++; hi--;
}
else if (nums[lo] + nums[hi] < sum) lo++;
else hi--;
}
}
}
return res;
}
public List<List<int>> kSum(int[] nums, int target, int k, int index)
{
List<List<int>> res = new List<List<int>>();
if (nums == null || nums.Length < k) return res;
Array.Sort(nums);
int len = nums.Length;
int max = nums[len - 1];
if (k * nums[0] > target || k * max < target)
{
return res;
}
if (index >= len)
{
return res;
}
if (k == 2)
{
int i = index, j = len - 1;
while (i < j)
{
if (nums[i] + nums[j] == target)
{
res.Add(new List<int> { nums[i], nums[j] });
while (i < j && nums[i] == nums[i + 1]) i++;
while (i < j && nums[j] == nums[j - 1]) j--;
i++; j--;
}
else if (nums[i] + nums[j] < target) i++;
else j--;
} //while循环结束
}
else
{
for (int i = index; i < len - k + 1; i++)
{
List<List<int>> temp = kSum(nums, target - nums[i], k - 1, i + 1);
if (temp != null && temp.Count != 0)
{
for(int m =0;m< temp.Count;m++)
{
temp[m].Add( nums[i]);
}
res.AddRange(temp);
}
while (i < len - 1 && nums[i] == nums[i + 1])
{
i++;
}
}//for循环结束
}
return res;
}