Combination Sum II

来源:互联网 发布:js if else 简写 编辑:程序博客网 时间:2024/06/05 12:03

题目:跟http://blog.csdn.net/xiaoxiaoluo/article/details/44516963些许不同,候选集合中的每个元素只能选择一次。

第二种情况中,遍历到当前的元素不选时,需要找到不等于当前值的下一个位置继续递归


class Solution {public:    vector<vector<int> > combinationSum2(vector<int> &num, int target) {        vector<vector<int> > result;        vector<int> combination;        if(!num.empty()) {            sort(num.begin(), num.end());            combinationSumAssist(num, 0, target, result, combination);        }        return result;    }private:    void combinationSumAssist(vector<int> &candidates, int index, int target, vector<vector<int> > &result, vector<int> &combination) {        if(index >= candidates.size()) {            return;        }        int temp = target - candidates[index];        int next = nextIndex(candidates, index + 1, candidates[index]);        if(temp >= 0) {            combination.push_back(candidates[index]);            if(temp == 0) {                result.push_back(combination);            } else {                combinationSumAssist(candidates, index + 1, temp, result, combination);            }            combination.pop_back();        }        if(next != -1) {            combinationSumAssist(candidates, next, target, result, combination);        }    }        int nextIndex(vector<int> &candidates, int index, int val) {        int low = index, high = candidates.size() - 1;        int mid = -1;        while(low <= high) {            mid = (low + high) >> 1;            if(candidates[mid] <= val) {                low = mid + 1;            } else {                high = mid - 1;            }        }        return candidates[mid] > val ? (high == candidates.size() - 1 ? -1 : high + 1): low;    }};


0 0