leetcode C++ 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 c
生活随笔
收集整理的這篇文章主要介紹了
leetcode C++ 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 c
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、思路:
? ? ? ? ? DFS深度搜索,直到所有元素都被遍歷。另外如果一組結果的求和大于target,剪枝返回
class Solution { public:vector<vector<int>> combinationSum(vector<int>& candidates, int target) {vector<vector<int>>res;vector<int>resList;DFS(candidates, res, resList, target, 0);return res;}void DFS(vector<int>& candidates, vector<vector<int>>&res, vector<int>resList, int &target, int index) {if (target == sum(resList)) {res.push_back(resList);resList.clear();return;}else if (target < sum(resList)) {resList.clear();return;}while (index < candidates.size()) {resList.push_back(candidates[index]);DFS(candidates, res, resList, target, index);index = index + 1;resList.pop_back();}}int sum(vector<int> resList) {int sum = 0;for (int i = 0; i < resList.size(); i++)sum += resList[i];return sum;} };?
總結
以上是生活随笔為你收集整理的leetcode C++ 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 c的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode C++ 28. 实现
- 下一篇: leetcode C++ 42. 接雨水