List<List<Integer>> kSum_Trim(int[] a, int target, int k) {
List<List<Integer>> result = new ArrayList<>();
if (a == null || a.length < k || k < 2) return result;
Arrays.sort(a);
kSum_Trim(a, target, k, 0, result, new ArrayList<>());
return result;
} void kSum_Trim(int[] a, int target, int k, int start, List<List<Integer>> result, List<Integer> path) {
int max = a[a.length - 1];
if (a[start] * k > target || max * k < target) return; if (k == 2) { // 2 Sum
int left = start;
int right = a.length - 1;
while (left < right) {
if (a[left] + a[right] < target) left++;
else if (a[left] + a[right] > target) right--;
else {
result.add(new ArrayList<>(path));
result.get(result.size() - 1).addAll(Arrays.asList(a[left], a[right]));
left++; right--;
while (left < right && a[left] == a[left - 1]) left++;
while (left < right && a[right] == a[right + 1]) right--;
}
}
}
else { // k Sum
for (int i = start; i < a.length - k + 1; i++) {
if (i > start && a[i] == a[i - 1]) continue;
if (a[i] + max * (k - 1) < target) continue;
if (a[i] * k > target) break;
if (a[i] * k == target) {
if (a[i + k - 1] == a[i]) {
result.add(new ArrayList<>(path));
List<Integer> temp = new ArrayList<>();
for (int x = 0; x < k; x++) temp.add(a[i]);
result.get(result.size() - 1).addAll(temp); // Add result immediately.
}
break;
}
path.add(a[i]);
kSum_Trim(a, target - a[i], k - 1, i + 1, result, path);
path.remove(path.size() - 1); // Backtracking
}
}
}

最新文章

  1. C# 中反射获取某类的子类和根据类型名动态创建对象
  2. mysql 索引2
  3. strlen和mb_strlen区别
  4. C++STL学习笔记_(4)queue
  5. iOS: ARC和非ARC下使用Block属性的问题
  6. 在redhat6下配置yum源的使用
  7. 树链剖分-SPOJ375(QTREE)
  8. Pyqt5学习系列
  9. 策略模式--List排序
  10. C# 插入超链接到PDF文档(3种情况)
  11. TCP/IP协议 网络层
  12. scss初学小结(转阮一峰老师SASS用法指南http://www.ruanyifeng.com/blog/2012/06/sass.html)
  13. angular 2 - 002 - 基本概念和使用
  14. Docker:Docker打包Web API成镜像并上传到Docker Hub(2)
  15. 如何在Vue项目中引入jQuery?
  16. 75.Java异常处理机制throws
  17. ReactJS实用技巧(2):从新人大坑——表单组件来看State
  18. c# winform+wcf代理上网的处理
  19. Mingw opencv Windows下命令行运行
  20. Windows 下的高 DPI 应用开发(UWP / WPF / Windows Forms / Win32)

热门文章

  1. DNF抽奖活动
  2. 【线段树】[Luogu P4198]楼房修建
  3. 在Linux下如果要使用接口标志要加什么头文件吗?因为我在使用IFF_UP时会出错,说是未定义
  4. c++内存相关函数
  5. [转]Delphi DLL的创建、静态 以及动态调用
  6. 在DELPHI中显示GIF动画
  7. BZOJ 1697: [Usaco2007 Feb]Cow Sorting牛排序(置换+贪心)
  8. 解决方案-CRM:Vtiger CRM
  9. JVM内核-原理、诊断与优化学习笔记(十):Class文件结构
  10. java之jvm学习笔记六(实践写自己的安全管理器)