leetcode39 --- combinationSum
生活随笔
收集整理的這篇文章主要介紹了
leetcode39 --- combinationSum
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1 題目
給定一個無重復元素的數組?candidates?和一個目標數?target?,找出?candidates?中所有可以使數字和為?target?的組合。
candidates?中的數字可以無限制重復被選取。
說明:
所有數字(包括?target)都是正整數。
解集不能包含重復的組合。?
2 解法
首先要對數組candidates進行遍歷, 數組candidates里面的每個元素都有選和不選兩種可能, 如果選的話, 剩下的target就是之前的target減去現在這個元素, 根據這種思想, 想到用遞歸的方法來解這個問題, 且需要進行回溯.
1. 需要維護一個vector, 里面有當前已經選擇的元素
2. 因為數組都為互不相同的正整數, 所以如果此時target為0, 那么就直接把當前的vector放入結果中, 返回
3. 如果索引值到達最大值, 也是返回
4. 在選擇一個元素完成后, 接下來就是不選這個元素繼續進行遞歸.
代碼:
void dfs(int target, int index, vector<int> &candidates, vector<int> &t_vec, vector<vector<int>> &res_vec) {//target是0, 把當前已經選的元素放進結果里if (target == 0) {res_vec.push_back(t_vec);return;}//遍歷到頭, 返回if (index == candidates.size()) {return;}//不選直接跳過dfs(target, index + 1, candidates, t_vec, res_vec);//選if (target >= candidates[index]) {t_vec.push_back(candidates[index]);dfs(target - candidates[index], index, candidates, t_vec, res_vec);//此時最后一個元素就是剛才選的元素, 把他刪除掉t_vec.pop_back();}}vector<vector<int>> combinationSum(vector<int>& candidates, int target) {vector<vector<int>> res_vec;vector<int> t_vec;dfs(target, 0, candidates, t_vec, res_vec);return res_vec;}?
總結
以上是生活随笔為你收集整理的leetcode39 --- combinationSum的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 3测试图片显示置信度_云上的移动性能测试
- 下一篇: leetcode 2 --- 两数相加