leetcode 40._回溯算法

题目:

https://leetcode-cn.com/problems/combination-sum-ii

给定一个数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用一次。

解答:

class Solution {
	public List<List<Integer>> combinationSum2(int[] candidates, int target) {
		List<List<Integer>> result = new ArrayList<>();
		Arrays.sort(candidates); // 去重的第一步
		comSum(candidates, target, result, new ArrayList<>(), 0);
		return result;
	}
    void comSum(int[] can, int tar, List<List<Integer>> res, List<Integer> canRes, int low){
        if(tar == 0){
            res.add(new ArrayList<>(canRes));
            return;
        }
        for(int i = low; i < can.length; ++i){
        	if(i > low && can[i-1] == can[i]) continue; // 去重的第二步
            if(can[i] <= tar){
                canRes.add(can[i]);
                comSum(can, tar-can[i], res, canRes, i+1);
                canRes.remove(canRes.size()-1);
            }else return;
        }
    }
}
发布了640 篇原创文章 · 获赞 12 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/xiamaocheng/article/details/105007076
今日推荐