Combination Sum

Description

Given a set of candidate numbers (C) 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.

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

Notice
* All numbers (including target) will be positive integers.
* Elements in a combination (a1, a2, … , ak) 
  must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
* The solution set must not contain duplicate combinations.
Example
given candidate set 2,3,6,7 and target 7, 
A solution set is: 
[
  [7] 
  [2, 2, 3]
]

Lintcode_ladder

Method

  1. x
  2. x

Example

  1. 1
class Solution {
public:
    /**
     * @param candidates: A list of integers
     * @param target:An integer
     * @return: A list of lists of integers
     */
    vector<vector<int> > combinationSum(vector<int> &candidates, int target) {
        // write your code here
        vector<vector<int>> result;
        if (candidates.empty() || target < 0) {
            return result;
        }
        vector<int> row;
        // make sure ascending order
        sort(candidates.begin(), candidates.end());
        helper(candidates, result, row, target, 0);
        return result;
    }
private:
    void helper(vector<int>& nums, vector<vector<int>>& result,
        vector<int>& row, int target, int start
    ) {
        if (target == 0) {
            result.push_back(row);
            return;
        }
        // pruning
        // if (target < 0) {
        //     return;
        // }
        int len = nums.size();
        int dup = -1;
        for (int i = start; i < len; ++i) {
            // de-dup
            if (dup != -1 && dup == nums[i]) {
                continue;
            }
            // pruning
            int rest = target - nums[i];
            if (rest < 0) {
                break;
            }
            row.push_back(nums[i]);
            // use i as the new index, we may reuse the current nums[i]
            helper(nums, result, row, rest, i);
            row.erase(row.begin() + row.size() - 1);
            dup = nums[i];
        }
        return;
    }
};

Similar problems

x

Tags

x

results matching ""

    No results matching ""