算法练习

组合总和(LeetCode 39 使用回溯 ,与77,78,9

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

题目

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

candidates 中的数字可以无限制重复被选取。

说明:

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

示例 1:

输入: candidates = [2,3,6,7], target = 7,
所求解集为:
[
[7],
[2,2,3]
]

示例 2:

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

解析

1.判断target值与当前值的大小关系,若target小与当前数组的candidates[idx]的值,则跳过继续
2.往List添加时要判断是否target值为0,为0则添加并返回,小与0则直接返回

代码

 public IList<IList<int>> CombinationSum(int[] candidates, int target) {
        IList<IList<int>> res = new List<IList<int>>();
        BackTrackTarget(0,candidates,target,res,new List<int>());
        return res;
    }

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

        for (int i = idx; i < candidates.Length; i++)
        {
            if(target<candidates[i]) continue; //小与则跳过
            temp.Add(candidates[i]);
            BackTrackTarget(i,candidates,target-candidates[i],res,temp);
            temp.RemoveAt(temp.Count-1);
        }
    }
上一篇 下一篇

猜你喜欢

热点阅读