前言:

这几天在做LeetCode 里面有2sum, 3sum(closest), 4sum等问题, 这类问题是典型的递归思路解题。该这类问题的关键在于,在进行求和求解前,要先排序Arrays.sort()可实现,而本文则着重探讨关于KSum问题。

leetcode求和问题描写叙述(K sum problem):

K sum的求和问题通常是这样子描写叙述的:给你一组N个数字(比方 vector num), 然后给你一个常数(比方 int target) ,我们的goal是在这一堆数里面找到K个数字,使得这K个数字的和等于target。

注意事项(constraints):

注意这一组数字可能有反复项:比方 1 1 2 3 , 求3sum, 然后 target = 6, 你搜的时候可能会得到 两组1 2 3, 1 2 3,1 来自第一个1或者第二个1, 可是结果事实上仅仅有一组。所以最后结果要去重。

引用:http://tech-wonderland.net/blog/summary-of-ksum-problems.html

KSum解决方法:

解决这类问题有两个方法:

1. 暴力法:这是最直接的简单方法。问题是这种方法在K 足够大的时候时间复杂度会竭尽无穷大,故不是有效的理想方案;

2. 递归法: 该方法是有技巧性的,关键在于寻找递归基,该问题的递归基是k = 2情况。

关于,3Sum,3Sum Closest,4Sum的解题思路和參考代码。

KSum java代码:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List; public class KSum { /**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//int[] s = new int[] {1,0,-1,0,-2,2 };
int[] s = new int[]{-500,-490,-471,-456,-422,-412,-406,-398,-381,-361,-341,-332,-292,-288,-272,-236,-235,-227,-207,-203,-185,-119,-59,-13,4,5,46,72,82,91,92,130,130,140,145,159,187,207,211,226,239,260,262,282,290,352,377,378,386,405,409,430,445,478,481,498};
System.out.println(" A solution set is: ");
List<List<Integer>> listArray = new ArrayList<List<Integer>>();
listArray = kSum(s,-3213);
for (int i = 0; i < listArray.size(); i++) {
System.out.println(listArray.get(i));
}
} public static List<List<Integer>> kSum(int[] nums, int target) { List<List<Integer>> result = new ArrayList<List<Integer>>();
Arrays.sort(nums);
result = recursionRoutin(nums,0,4,0);
return result;
} public static List<List<Integer>> recursionRoutin(int[] nums,int begin,int k,int target){
HashSet<List<Integer>> elementSet = new HashSet<List<Integer>>();
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<List<Integer>> subResult = new ArrayList<List<Integer>>();
//Recursion Base
if(k == 2){
int left = begin;
int right = nums.length - 1;
while(left < right){
int sum = nums[left] + nums[right];
if(sum == target){
List<Integer> taplet = new ArrayList<Integer>();
taplet.add(nums[left]);
taplet.add(nums[right]);
//Avoid reduplication
if(!elementSet.contains(taplet)){
result.add(taplet);
elementSet.add(taplet);
}
left ++;
right --;
}else if(sum < target){
left ++;
}else{
right --;
}
}
return result;
}else{ for(int i = begin;i < nums.length - k - 1;i ++){
subResult = recursionRoutin(nums,i + 1,k - 1,target - nums[i]);
//System.out.println(k + " " + subResult);
if(!subResult.isEmpty()){
for(int j = 0;j < subResult.size();j ++){
subResult.get(j).add(nums[i]);
result.add(subResult.get(j));
}
}
}
}
return result;
}
}

參考文章:http://tech-wonderland.net/blog/summary-of-ksum-problems.html

相关代码放在个人github:https://github.com/gannyee/LeetCode/

LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结的更多相关文章

  1. 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)

    转自  http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...

  2. 6.3Sum && 4Sum [ && K sum ] && 3Sum Closest

    3Sum Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find a ...

  3. LeetCode解题报告:Linked List Cycle && Linked List Cycle II

    LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...

  4. leetcode解题报告(2):Remove Duplicates from Sorted ArrayII

    描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...

  5. LeetCode解题报告—— 4Sum & Remove Nth Node From End of List & Generate Parentheses

    1. 4Sum Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + ...

  6. LeetCode 解题报告索引

    最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中......                        ...

  7. LeetCode解题报告—— 1-bit and 2-bit Characters & 132 Pattern & 3Sum

    1. 1-bit and 2-bit Characters We have two special characters. The first character can be represented ...

  8. LeetCode解题报告—— Container With Most Water & 3Sum Closest & Letter Combinations of a Phone Number

    1.  Container With Most Water Given n non-negative integers a1, a2, ..., an, where each represents a ...

  9. LeetCode解题报告—— Combination Sum & Combination Sum II & Multiply Strings

    1. Combination Sum Given a set of candidate numbers (C) (without duplicates) and a target number (T) ...

随机推荐

  1. 【D3 API 中文手冊】

    [D3 API 中文手冊] 声明:本文仅供学习所用,未经作者同意严禁转载和演绎 <D3 API 中文手冊>是D3官方API文档的中文翻译. 始于2014-3-23日,基于VisualCre ...

  2. 混合式框架-AngularJS

    简单介绍   AngularJS是为了克服HTML在构建应用上的不足而设计的.HTML是一门非常好的为静态文本展示设计的声明式语言,但要构建WEB应用的话它就显得乏力了.所以我做了一些工作(你也能够认 ...

  3. 修改android的wifi客户端名称的两种方法

    修改android的wifi客户端名称的两种方法     手机连接到无线路由时,在dhcp的客户端列表里面是这样的名称"android-89425253e5de3a2",这就是安卓 ...

  4. python使用大漠插件进行脚本开发的尝试(一)

    关于游戏脚本是纯然的小白,记一下学习过程遇到的问题.是在win10系统下对PC端的游戏进行脚本编辑,不知道会不会半途放弃. 一.大漠插件 大漠插件在游戏脚本编辑过程中是比较常见的工具,按我理解大致做的 ...

  5. STM32之CAN通讯接收过滤器过滤分析

    一.前言 学习了CAN通讯,底层的东东CAN控制器已经帮你处理完成,也就是CAN通讯协议已经做好,你按协议格式往对应的位扔数据发送就好,所以使用CAN通讯,我们只需要去关心制定发送的数据间的协议,也就 ...

  6. 2.1 使用eclipse4.4 搭建 maven简单结构项目。

    1.前言 1.本博客面向0基础开发人员. 2.本博客为系列博客.<1.X>系列为服务器数据库相关技术,前几章为简单搭建linux+tomcat+mysql+nginx+redis.< ...

  7. 在手机中预置联系人/Service Number

    代码分为两部分: Part One 将预置的联系人插入到数据库中: Part Two 保证预置联系人仅仅读,无法被编辑删除(在三个地方屏蔽对预置联系人进行编辑处理:联系人详情界面.联系人多选界面.新建 ...

  8. js数组遍历和对象遍历小结

    数组的遍历 for循环 for(var j = 0,len = arr.length; j < len; j++){ console.log(arr[j]); } forEach,性能比for还 ...

  9. 【前端切图】用css画一个卡通形象-小猪佩奇

    最近在腾讯云技术社区遇到了一位奇才,用css画出了一个社会人小猪佩奇,不得不服.研究了一下他的文章https://segmentfault.com/a/1190000014909658,感觉甚是有趣, ...

  10. 洛谷——P1046 陶陶摘苹果

    https://www.luogu.org/problem/show?pid=1046 题目描述 陶陶家的院子里有一棵苹果树,每到秋天树上就会结出10个苹果.苹果成熟的时候,陶陶就会跑去摘苹果.陶陶有 ...