Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution.
1 2 3
Example: Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
To solve this problem, one possible way is to use DFS to generate all the 3-element subsets of the given input array(just like what we have done in the LeetCode problem Subsets):
publicclassThreeSumClosest{ publicintthreeSumClosest(int[] nums, int target){ if (nums.length < 3) { return0; } Arrays.sort(nums);
int result = nums[0] + nums[1] + nums[2]; for (int i = 0; i < nums.length; i++) {
int left = i + 1; int right = nums.length - 1; while (left < right) { int sum = nums[i] + nums[left] + nums[right]; if (Math.abs(target - sum) < Math.abs(target - result)) { result = sum; }