日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

leetcode C++ 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 c

發(fā)布時(shí)間:2025/4/16 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 leetcode C++ 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 c 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

一、思路:

? ? ? ? ? DFS深度搜索,直到所有元素都被遍歷。另外如果一組結(jié)果的求和大于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;} };

?

總結(jié)

以上是生活随笔為你收集整理的leetcode C++ 39. 组合总和 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。 c的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。