前言:

这几天在做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. shell项目-分发系统-expect讲解

    shell项目-分发系统-expect讲解 yum install -y expect 1. 自动远程登录 #! /usr/bin/expect set host "192.168.133. ...

  2. ST和LCA和无根树连接

    #include <stdio.h> #include <iostream> #include <string.h> #include <algorithm& ...

  3. 微信小程序从零开始开发步骤(二)创建小程序页面

    上一章注册完小程序,添加新建的项目,大致的准备开发已经完成,本章要分享的是 要创建一个简单的页面了,创建小程序页面的具体几个步骤: 1. 在pages 中添加一个目录 选中page,右击鼠标,从硬盘打 ...

  4. 【Hello 2018 B】Christmas Spruce

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 写个dfs看看是不是每个节点都有3个叶子节点就可以了. [代码] #include <bits/stdc++.h> us ...

  5. 【Uva 10163】Storage Keepers

    [Link]: [Description] 你有n(n≤100)个相同的仓库.有m(m≤30)个人应聘守卫,第i个应聘者的能力值 为Pi(1≤Pi≤1000).每个仓库只能有一个守卫,但一个守卫可以看 ...

  6. 安卓使用WebView下载文件,安卓实现软件升级功能

    由于调用系统默认浏览器下载更新,造成用户体验非常不好,所以决定在webview中直接下载系统更新.然后直接安装. 由于要下载,所以必须用webview,联网权限这里不说了,直接写在manifafest ...

  7. layoutParams-动态更改某个控件的margin

    其实它的方法也非常的简单,如下 LinearLayout.LayoutParams layoutParams = (LayoutParams) bt1.getLayoutParams(); int a ...

  8. 【Educational Codeforces Round 35 D】Inversion Counting

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 排列中交换任意两个数字. 排列的逆序对个数的奇偶性会发生变化. 翻转这个过程其实就是len/2对数字发生交换. 交换了偶数次的话,不 ...

  9. iOS界面生命周期过程具体解释

    开发过Android的人都知道,每个Android界面就是一个Activity,而每个Activity都会有自己的生命周期, 有一系列方法会控制Activity的生命周期.如:onCreate(),o ...

  10. Spring3拦截引发的问题——WEB开发中的client路径

    什么是client路径? 第一类.也就是html或js文件等client訪问的文件里的路径,这里包含一些资源文件的引入(js.css还有各种图片等),或是跳转到静态html页面,总之获取的都是静态资源 ...