题解 | #最接近的三数之和#
最接近的三数之和
http://www.nowcoder.com/practice/f889497fd1134af5af9de60b4d13af23
import java.util.*;
public class Solution {
public int ans = 100000;
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
public int ClosestSum(int[] nums, int target) {
// write code here
if (3 == nums.length) {
return nums[0] + nums[1] + nums[2];
}
process(nums, 0, 0, 0, target);
return ans;
}
public void process(int[] nums, int index, int previousTotal, int numbers, int target) {
if (numbers == 3) {
ans = Math.abs(previousTotal - target) < Math.abs(ans - target) ? previousTotal : ans;
return;
}
if (index >= nums.length) {
return;
}
process(nums, index + 1, previousTotal, numbers, target);
process(nums, index + 1, previousTotal + nums[index], numbers + 1, target);
}
}