LeetCode解题报告--2Sum, 3Sum, 4Sum, K Sum求和问题总结
前言:
这几天在做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求和问题总结的更多相关文章
- 求和问题总结(leetcode 2Sum, 3Sum, 4Sum, K Sum)
转自 http://tech-wonderland.net/blog/summary-of-ksum-problems.html 前言: 做过leetcode的人都知道, 里面有2sum, 3sum ...
- 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 ...
- LeetCode解题报告:Linked List Cycle && Linked List Cycle II
LeetCode解题报告:Linked List Cycle && Linked List Cycle II 1题目 Linked List Cycle Given a linked ...
- leetcode解题报告(2):Remove Duplicates from Sorted ArrayII
描述 Follow up for "Remove Duplicates": What if duplicates are allowed at most twice? For ex ...
- 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 + ...
- LeetCode 解题报告索引
最近在准备找工作的算法题,刷刷LeetCode,以下是我的解题报告索引,每一题几乎都有详细的说明,供各位码农参考.根据我自己做的进度持续更新中...... ...
- 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 ...
- 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 ...
- 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) ...
随机推荐
- C++遍历目录+_finddata_t结构体用法
Struct _finddata_t是用来存储文件各种信息的结构体,使用这个结构体要引用的头文件为“ #include <io.h>”它的结构体定义如下: struct _finddata ...
- C++里面virtual函数及虚表大小
实验了下面的函数: #include <vector> #include <iostream> using namespace std; class A { public: v ...
- HTTP (httpwebrequest)
1.GET请求: public static string Get(string url) { string buffer = ""; try { HttpWebRequest r ...
- [Express] Upload Files with Express
In this lesson we create a new Express web server app for handling file uploads and persisting them ...
- Android使用BroadCastRecevier广播实现接收短信,并利用Toast弹出显示内容
在上一篇文章 Android简单实现BroadCastReceiver广播机制 中简单的实现了一个广播机制,这里利用BroadCarstRecevier实现一个接收短信并显示内容的案例,当然至于接收到 ...
- WdatePicker日期控件的使用
将压缩包中的文件连带文件夹添加到项目中去,注意要完整的添加到项目中去,不要更改了其目录结构 然后在aspx页面中直接使用即可: 首先引入: <script src="/Controls ...
- Zabbix 监控搭建
Zabbix官网地址:https://www.zabbix.com/download 1.服务端 1.操作前安装好Mysql数据库 配置yum源,安装部署Zabbix rpm -i http://re ...
- Activity学习
http://www.360doc.com/content/13/1106/11/203871_327110236.shtml http://www.jianshu.com/p/e6971e8a8da ...
- 【Java】Java Socket 通信演示样例
用socket(套接字)实现client与服务端的通信. 这里举两个样例: 第一种是每次client发送一个数据,服务端就做一个应答. (也就是要轮流发) 另外一种是client能够连续的向服务端发数 ...
- BPX-tree
写的匆忙 估计有BUG 修改后 会去掉这个 说明 /** * @author shuly * @date 2017/6/5. */ // hint 一日为叶,终身为叶, 最后还是要转换成 <链 ...