算法练习

组合总和 II(LeetCode 40 与39类似)

2020-02-21  本文已影响0人  倚剑赏雪

题目

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

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

说明:

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

示例 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和candidates[i]的大小
3.若target为0则添加

代码

 public IList<IList<int>> CombinationSum2(int[] candidates, int target) {
        Array.Sort(candidates); // 排序,以便去重
        IList<IList<int>> res = new List<IList<int>>();
        BackTrackTarget2(0,candidates,target,res,new List<int>());
        return res;
    }

    void BackTrackTarget2(int idx, int[] candidates, int target, IList<IList<int>> res, IList<int> temp)
    {
        if (target == 0)
        {
            res.Add(new List<int>(temp));
            return;
        }

        for (int i = idx; i < candidates.Length; i++)
        {
            if(target-candidates[i] <0){break;}
            if(i>idx&& candidates[i-1] == candidates[i]) continue;
            temp.Add(candidates[i]);
            BackTrackTarget2(i+1,candidates,target-candidates[i],res,temp);
            temp.RemoveAt(temp.Count-1);
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读