Leetcode: 40. Combination Sum II

Description

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

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

Example

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8, 
A solution set is: 
[
    [1, 7],
    [1, 2, 5],
    [2, 6],
    [1, 1, 6]
]

思路

  • dfs
  • 由于每个数字只可以用一次,所以进入递归的下一个起点应该是当前位置的下个位置
  • 注意可能出现重复情况

代码

class Solution {
public:
    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> tmp;
        
        sort(candidates.begin(), candidates.end());
        dfs(candidates, target, candidates.size(), 0, res, tmp, 0);
        
        return res;
    }
    
    bool dfs(vector<int>& candidates, int target, int len, int t, vector<vector<int>> &res,
            vector<int>& tmp, int sum){
        if(sum == target){
            res.push_back(tmp);
            return true;
        }
        else if(sum < target){
            bool flag = false;
            for(int i = t; i < len; ++i){
                //考虑当前元素同前一个是重复的情况
                if(i > t && candidates[i] == candidates[i - 1]) continue;
                if(sum + candidates[i] > target)
                    return false;
                    
                sum += candidates[i];
                tmp.push_back(candidates[i]);
                
                //从i+1位置进入下一层递归
                flag = dfs(candidates, target, len, i + 1, res, tmp, sum);
                sum -= candidates[i];
                tmp.pop_back();
                if(flag)
                    break;
            }
        }
        
        return false;
    }
};
posted @ 2017-05-11 17:18  JeffLai  阅读(121)  评论(0编辑  收藏  举报