1. 程式人生 > >[LeetCode] Combination Sum

[LeetCode] Combination Sum

ica example 求解 post 每次 not sum oid tor

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

使用回溯法求解。

主要是對於輔助函數helper的構建

void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& candidates, int target, int idx);

idx為遍歷的頭索引。

helper(res, tmp, candidates[i], target - candidates[i], i);

每次將target更新為選擇池中的剩余目標值。i不變是因為組成target的值允許重復。

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<vector<int>> res;
        vector<int> tmp;
        int idx = 0;
        helper(res, tmp, candidates, target, idx);
        
return res; } void helper(vector<vector<int>>& res, vector<int>& tmp, vector<int>& candidates, int target, int idx) { if (target < 0) { return; } else if (target == 0) { res.push_back(tmp); } else { for (int i = idx; i < candidates.size(); i++) { tmp.push_back(candidates[i]); helper(res, tmp, candidates, target - candidates[i], i); tmp.pop_back(); } } } }; // 16 ms

[LeetCode] Combination Sum