【两次过】Lintcode 59. 最接近的三数之和

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/majichen95/article/details/88925467

给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。

样例

例1:

输入:[2,7,11,15],3
输出:20
解释:
2+7+11=20

例2:

输入:[-1,2,1,-4],1
输出:2
解释:
-1+2+1=2

挑战

O(n^2) 时间, O(1) 额外空间。

注意事项

只需要返回三元组之和,无需返回三元组本身


解题思路:

标准DFS解法。需要增加sum变量来表示截至递归到当前层的和

public class Solution {
    /**
     * @param numbers: Give an array numbers of n integer
     * @param target: An integer
     * @return: return the sum of the three integers, the sum closest target.
     */
    public int threeSumClosest(int[] numbers, int target) {
        // write your code here
        res = Integer.MAX_VALUE;
        
        dfs(numbers, target, new ArrayList<Integer>(), 0, 0);
        
        return res;
    }
    
    private int res;
    
    private void dfs(int[] numbers, int target, List<Integer> list, int sum, int index){
        if(list.size() == 3){
            if(Math.abs(sum-target) < Math.abs(res-target))
                res = sum;
            
            return;
        }
        
        for(int i=index; i<numbers.length; i++){
            list.add(numbers[i]);
            
            dfs(numbers, target, list, sum+numbers[i], i+1);
            
            list.remove(list.size()-1);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/majichen95/article/details/88925467
今日推荐