首页 > 搜索 > DFS搜索 > LeetCode-Combination Sum[DFS]
2014
11-18

LeetCode-Combination Sum[DFS]

Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ ak).
  • The solution set must not contain duplicate combinations.

For example, given candidate set 2,3,6,7 and target 7,
A solution set is:
[7]
[2, 2, 3]

标签: Array Backtracking
分析

代码1

// LeetCode, Combination Sum
// 时间复杂度O(n!),空间复杂度O(n)
class Solution {
public:
    vector<vector<int> > combinationSum(vector<int> &nums, int target) {
        sort(nums.begin(), nums.end());
        vector<vector<int> > result; // 最终结果
        vector<int> intermediate; // 中间结果
        dfs(nums, target, 0, intermediate, result);
        return result;
    }

private:
    void dfs(vector<int>& nums, int gap, int start, vector<int>& intermediate,
            vector<vector<int> > &result) {
        if (gap == 0) {  // 找到一个合法解
            result.push_back(intermediate);
            return;
        }
        for (size_t i = start; i < nums.size(); i++) { // 扩展状态
            if (gap < nums[i]) return; // 剪枝

            intermediate.push_back(nums[i]); // 执行扩展动作
            dfs(nums, gap - nums[i], i, intermediate, result);
            intermediate.pop_back();  // 撤销动作
        }
    }
};

Java代码:

public class Solution {
    public static List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<List<Integer>>();
        List<Integer> list = new ArrayList<Integer>();
		
        Arrays.sort(candidates);
		combinationSumRecur(candidates,0, target, list, res);
		//System.out.println(res.size());
		//System.out.println(res);
		return res;
    }
	
	public  static void combinationSumRecur(int candidates[],int k,int target,List<Integer> list,List<List<Integer>> res){
		if(target < 0 || k >= candidates.length) return;
		if(0 == target){
			res.add(new ArrayList<>(list));
			return;
		}
		list.add(candidates[k]);
		combinationSumRecur(candidates, k, target-candidates[k], list, res);
		list.remove(list.size()-1);
		while(  k+1 < candidates.length && candidates[k] == candidates[k+1]) k++;
		combinationSumRecur(candidates, k+1,  target, list, res);
	}
}

相关题目
Combination Sum II


  1. 第二种想法,我想来好久,为啥需要一个newhead,发现是把最后一个节点一直返回到嘴上面这层函数。厉害,这道题之前没样子想过。