...
Code Block |
---|
// nums should be already sorted func nSum(nums []int, target int, n int) (results [][]int) { if n == 2 { return twoSum(nums, target) } i := 0 for i < len(nums)-n+1 { partResults := nSum(nums[i+1:], target-nums[i], n-1) for _, r := range partResults { results = append(results, append([]int{nums[i]}, r...), ) } for v := nums[i]; i < len(nums)-n+1 && nums[i] == v; i++ {} } return } func twoSum(nums []int, target int) (results [][]int) { i, j := 0, len(nums)-1 for i < j { sum := nums[i] + nums[j] if sum == target { results = append(results, []int{nums[i], nums[j]}) for v := nums[i]; i < len(nums) && nums[i] == v; i++ {} for v := nums[j]; j >= 0 && nums[j] == v; j-- {} } else if sum < target { for v := nums[i]; i < len(nums) && nums[i] == v; i++ {} } else { for v := nums[j]; j >= 0 && nums[j] == v; j-- {} } } return } // 使用示例(利用 4Sum)做演示 func fourSum(nums []int, target int) (results [][]int) { sort.Ints(nums) return nSum(nums, target, 4) } |