Two Sum I
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
分析:如果数组已经排序完,那么只需要双指针从两端往中间夹即可。但是没有排序的话,先排序复杂度就已经O(nlogn)了,所以没法用排序法。事实上是有O(n)的hash法:首先遍历一遍,全部放入hashtable(unordered_set)中,复杂度为O(n);然后再对于每个数x,都在hashtable中找target - x的数在不在其中,如果在,就结束,因为题目说假设只有一个答案,复杂度为O(n);总复杂度为O(n)。
Two Sum II - Input array is sorted
不用排序的排序法,因为数组已经排序完,从两端往中间夹的复杂度与hash法一样也为O(n);但理论时间开销应该比hash法小的。
Two Sum III - Data structure design
略
3 Sum
与Two Sum题目类似,二元换成了三元。两种解法,复杂度均为O(n^2)
3 Sum Closest
这个3 Sum的排序法,可解出,复杂度为O(n ^ 2)。没法用hash法。
3 Sum Smaller
Given an array of n integers nums and a target, find the number of index triplets i, j, k with 0 <= i < j < k < n that satisfy the condition nums[i] + nums[j] + nums[k] < target.
For example, given nums = [-2, 0, 1, 3], and target = 2.
Return 2. Because there are two triplets which sums are less than 2:
[-2, 0, 1]
[-2, 0, 3]
Follow up: Could you solve it in O(n^2) runtime?
暴力解法是O(n^3)。用Sum的排序法,可接出,复杂度为O(n ^ 2)。
没法用hash法,顶多用multimap做,但复杂度为O(n^2*logn)。
4 Sum
从二元到三元再到四元
【总结】到这里为止,我们基本也可以总结出这NSum类型的解法:
【Combination Sum I】
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.
Note:
For example, given candidate set 2,3,6,7
and target 7
,
A solution set is: [7]
[2, 2, 3]
【Combination Sum II】
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.
For example, given candidate set 10,1,2,7,6,1,5
and target 8
,
A solution set is: [1, 7]
[1, 2, 5]
[2, 6]
[1, 1, 6]
【Combination Sum III】
Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Ensure that numbers within the set are sorted in ascending order.
Example:
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
思路
原文:http://www.cnblogs.com/littletail/p/5337448.html