Skip to content
本页目录

0039-组合总和

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

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。 candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

输入: candidates = [2,3,5], target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2], target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 1 <= candidates[i] <= 200
  • candidate 中的每个元素都 互不相同
  • 1 <= target <= 500

思路

组合问题,使用回溯法。 遍历 candidates 递归,结束条件为 >= 7 ,如果 ==7 就输出结果

参考代码

csharp
public class Solution {

	List<IList<int>> result = new List<IList<int>>();

	private List<int> CopyList(List<int> list){
		List<int> newList = new List<int>();
		for(int i=0; i<list.Count; i++){
			newList.Add(list[i]);
		}
		return newList;
	}

	private void dfs(int[] candidates, int target, List<int> list, int curSum){
		if(curSum > target){
			return;
		}
		if(curSum == target){
			//输出结果
			result.Add(CopyList(list));
			return;
		}
		for(int i=0; i<candidates.Length; i++){
            //当后面的数字出现的时候,不要重复计算前面的数
            if(list.Count == 0 || candidates[i] >= list[list.Count-1]){ 
                list.Add(candidates[i]);
                dfs(candidates,target,list,curSum+candidates[i]);
                //回溯:删除最后一个数
                list.RemoveAt(list.Count-1);
            }		
		}
	}

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

复习:20220512

csharp
public class Solution {
    List<IList<int>> result = new List<IList<int>>();
    private void dfs(int[] candidates, int target, List<int> list){
        if(target < 0){
            return;
        }
        if(target == 0){ //满足条件输出
            result.Add(new List<int>(list));
            return;
        }
        for(int i=0; i<candidates.Length; i++){
            if(list.Count == 0 || candidates[i] >= list[list.Count-1]){ //不要重复循环到前面的数字
                list.Add(candidates[i]);
                dfs(candidates,target - candidates[i],list);
                list.RemoveAt(list.Count-1);
            }
        }
    }

    public IList<IList<int>> CombinationSum(int[] candidates, int target) {
        List<int> list = new List<int>();
        dfs(candidates,target,list);
        return result;
    }
}

Released under the MIT License.