1. 程式人生 > >【LeetCode】106.Combination Sum

【LeetCode】106.Combination Sum

題目描述(Medium)

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

The same repeated number may be chosen from candidates

 unlimited number of times.

Note:

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

題目連結

https://leetcode.com/problems/restore-ip-addresses/description/

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

演算法分析

dfs,若當前累加沒有超過目標,則下一個數的累加,仍然從當前位置開始;若當前累加超過目標,則當前位進入下一個數。

提交程式碼:

class Solution {
public:
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        vector<int> solution;
        dfs(candidates, solution, target, 0, 0);
        return this->result;
    }

private:
    vector<vector<int>> result;
    void dfs(vector<int>& candidates, vector<int>& solution, int target, 
             int cur_sum, int start) {
        if (cur_sum == target) {
            this->result.push_back(solution);
            return;
        }
                
        for (int i = start; i < candidates.size(); ++i) {
            cur_sum += candidates[i];
            solution.push_back(candidates[i]);
            if (cur_sum <= target) {
                dfs(candidates, solution, target, cur_sum, i);
            }
            solution.pop_back();
            cur_sum -= candidates[i];
        }
    }
};