前言:

这几天在做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. deep-in-es6(六)

    箭头函数 Arrow Functions 箭头函数在JavaScript诞生是就存在,JavaScript建议在HTML注释内包裹行内脚本,这样可以避免不支持JS代码的浏览器将JS显示为文本. < ...

  2. TOJ 2233 WTommy's Trouble

    2233.   WTommy's Trouble Time Limit: 2.0 Seconds   Memory Limit: 65536KTotal Runs: 1499   Accepted R ...

  3. 洛谷 P2021 faebdc玩扑克

    P2021 faebdc玩扑克 题目背景 faebdc和zky在玩一个小游戏 题目描述 zky有n个扑克牌,编号从1到n,zky把它排成一个序列,每次把最上方的扑克牌放在牌堆底,然后把下一张扑克牌拿出 ...

  4. POJ 1426 Find The Multiple (DFS / BFS)

    题目链接:id=1426">Find The Multiple 解析:直接从前往后搜.设当前数为k用long long保存,则下一个数不是k*10就是k*10+1 AC代码: /* D ...

  5. emacs 为什么找不到运行程序?

    我记得前段时间有个朋友问我为什么在emacs中打不开matlab程序?明明在terminal下是能打开的,却在emacs中不行. 今天自己最终遇到了相似的问题,我今天安装racket 6.0.安装好后 ...

  6. 洛谷P3165 [CQOI2014]排序机械臂

    题目描述 为了把工厂中高低不等的物品按从低到高排好序,工程师发明了一种排序机械臂.它遵循一个简单的排序规则,第一次操作找到摄低的物品的位置P1,并把左起第一个至P1间的物品反序:第二次找到第二低的物品 ...

  7. Day3晚笔记

    DEV C++扩展栈空间 -Wl,--stack=64000000000 带权二分图匹配 建一个超级源点S,超级汇点T 把左边的点的点权作为权值,连一条S到左边的点的边 把右边的点的点权作为权值,连一 ...

  8. jmeter响应数据中文乱码问题

    进入jmeter安装文件目录:D:\Program File\apache-jmeter-2.13\apache-jmeter-2.13\bin\ 修改jmeter.properties文件,在最下方 ...

  9. java匿名内部类使用场景列举

    示例一: package com;      interface Operation {       double operateTwoIntNum(int a, int b);   }      p ...

  10. python路径找类并获取静态字段

    Python通过路径找类并获取其中大写的静态字段 settings.py class Foo: DEBUG = True TEST = True xx.py import importlib path ...