40.组合总和 II

题目描述

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

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

说明:

所有数字(包括 target)都是正整数。
解集不能包含重复的组合。 

示例1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
所求解集为:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

示例2:

输入: candidates = [2,5,2,1,2], target = 5,
所求解集为:
[
  [1,2,2],
  [5]
]

思路

1.这道题可以使用回溯算法求解,原理和 组合总和 基本一致。
2.记录当前元素的位置,以及在结果集中加入当前元素之后的target数值,下次开始的索引是本次加一。
3.若target<0则说明无解,要进行回溯操作,跳回上一个元素的位置。
4.若target=0则说明该组合是目标解之一,将其加入结果集之后,进行回溯操作。
5.最后将结果集进行去重处理。

Java代码实现

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> ans = new ArrayList<>();
        backtrack2(candidates,target,0,res,ans);
        return res;
    }

    private void backtrack2(int[] candidates,int target,int start,List<List<Integer>> res,List<Integer> ans){
        if(target<0)
            return;
        if(target == 0){
            res.add(new ArrayList<>(ans));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            ans.add(candidates[i]);
            backtrack2(candidates,target-candidates[i],i+1,res,ans);
            ans.remove(ans.size()-1);
        }
    }

Golang代码实现

func combinationSum2(candidates []int, target int) [][]int {
    sort.Ints(candidates)
    res := make([][]int,0)
    combinationSum2DFS(candidates,0,target,&res,[]int{})
    return res
}

func combinationSum2DFS(candidates []int,curIndex int, target int,res *[][]int,cur []int){
    if target < 0 {
        return
    }
    if target == 0{
        copyCur := make([]int,len(cur))
        copy(copyCur,cur)
        *res = append(*res,copyCur)
    }

    for i:=curIndex; i<len(candidates);i++ {
        if i>curIndex && candidates[i] == candidates[i-1]{
            continue
        }
        cur = append(cur,candidates[i])
        combinationSum2DFS(candidates,i+1,target-candidates[i],res,cur)
        cur = cur[:len(cur)-1]
    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务