LeetCode40. 组合总和 II

题意

  • 给一个数组和target, 找出数组中所有和为target的组合

方法

  • DFS

代码

class Solution {
private:
    vector<vector<int>> res;
    vector<int> tmp;

public:
    int getNextNumberIndex(vector<int>& candidates, int i)  //寻找下一个不同元素的下标
    {
        int next = i;
        while (next < candidates.size() && candidates[next] == candidates[i])
        {
            ++ next;
        }

        return next;
    }

    void dfs(vector<int>& candidates, int i, int target)    //i为当前元素的下标
    {
        if (target == 0)
        {
            res.push_back(tmp);
        }
        else if (target > 0 && i < candidates.size())
        {
            tmp.push_back(candidates[i]);   //选择当前元素
            dfs(candidates, i + 1, target - candidates[i]);
            tmp.pop_back();                 //不选当前元素,选择下一个不同元素
            dfs(candidates, getNextNumberIndex(candidates, i), target);
        }
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        sort(candidates.begin(), candidates.end());         //首先排序

        dfs(candidates, 0, target);

        return res;
    }
};
posted @ 2022-11-07 18:35  Figure_at_a_Window  阅读(19)  评论(0)    收藏  举报