生活随笔
收集整理的這篇文章主要介紹了
LeetCode 40 组合总和 II
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目描述
給定一個數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和為 target
的組合。candidates 中的每個數字在每個組合中只能使用一次。
題解
對candidates數組進行排序。
代碼
class Solution
{
public
:void dfs(vector
<int>& candidates
,vector
<int>& tmp
,int start
,int sum
,int target
){if (sum
==target
){res
.push_back(tmp
);return;}for (int i
=start
;i
<candidates
.size();i
++){if (i
!=start
&&candidates
[i
]==candidates
[i
-1]) continue;if (sum
+candidates
[i
]<=target
){tmp
.push_back(candidates
[i
]);dfs(candidates
,tmp
,i
+1,sum
+candidates
[i
],target
);tmp
.pop_back();}}}vector
<vector
<int>> combinationSum2(vector
<int>& candidates
, int target
) {vector
<int> tmp
;sort(candidates
.begin(),candidates
.end());dfs(candidates
,tmp
,0,0,target
);return res
;}vector
<vector
<int>> res
;
};
總結
以上是生活随笔為你收集整理的LeetCode 40 组合总和 II的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。