1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public: const static int maxn = 1e5 + 10; const static int maxm = 1e5 + 10; const static int INF = 0x3f3f3f3f; vector<vector<int>> ans; void dfs(int step, int sum, int target, vector<int> &cur, vector<int> &nums, vector<bool>& vis) { if (sum == target) { ans.emplace_back(cur); return; } if (sum > target) return; if (step == nums.size()) return; if(step > 0 && nums[step] == nums[step - 1] && !vis[step - 1]) { dfs(step + 1, sum, target, cur, nums, vis); } else { cur.emplace_back(nums[step]); vis[step] = true; dfs(step + 1, sum + nums[step], target, cur, nums, vis); vis[step] = false; cur.pop_back(); dfs(step + 1, sum, target, cur, nums, vis); }
} vector<vector<int>> combinationSum2(vector<int> &candidates, int target) { vector<int> cur; vector<bool> vis(candidates.size(), false); sort(candidates.begin(), candidates.end()); dfs(0, 0, target, cur, candidates, vis); return ans; } };
|