您的位置:首页 > 其它

[leetcode]18. 4Sum

2016-10-18 23:25 453 查看
Given an array S of n integers, are there elements a, b, c, and d in S such that a + b + c + d =
target? Find all unique quadruplets in the array which gives the sum of target.

Note: The solution set must not contain duplicate quadruplets.
For example, given array S = [1, 0, -1, 0, -2, 2], and target = 0.

A solution set is:
[
[-1,  0, 0, 1],
[-2, -1, 1, 2],
[-2,  0, 0, 2]
]

之前ThreeSum就用了通用的KSum算法,当时用了java,这里用golang.

func fourSum(nums []int, target int) [][]int {
qsort(&nums)
return KSum(nums, 0, 4, target)
}
func KSum(nums []int, start int, k int, target int) [][]int {
var result [][]int = [][]int{}
if k == 2 {
s := start
e := len(nums) - 1
for s < e {
if nums[s]+nums[e] < target {
s++
} else if nums[s]+nums[e] > target {
e--
} else {
tmp := []int{nums[s], nums[e]}
result = append(result, tmp)
s++
e--
for s < e && nums[s-1] == nums[s] {
s++
}
for s < e && nums[e+1] == nums[e] {
e--
}

}
}
} else {
for i := start; i < len(nums); i++ {
if i > start && nums[i] == nums[i-1] {
continue
}
mList := KSum(nums, i+1, k-1, target-nums[i])
if len(mList) > 0 {
for _, arr := range mList {
arr = append(arr, nums[i])
result = append(result, arr)
}
}
}

}
return result
}
func qsort(nums *[]int) {
partition(nums, 0, len(*nums)-1)
}
func partition(nums *[]int, start, end int) {
if start >= end {
return
}
var flag int = (*nums)[start]
var index int = start
var s int = start
var e int = end
for s <= e {
for s <= e && (*nums)[e] >= flag {
e--
}
if s <= e {

(*nums)[index] = (*nums)[e]
index = e
e--

}

for s <= e && (*nums)[s] <= flag {
s++
}
if s <= e {

(*nums)[index] = (*nums)[s]
index = s
s++

}
}

(*nums)[index] = flag
partition(nums, start, index-1)
partition(nums, index+1, end)
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: