Combination Sum (lintcode 135)

来源:互联网 发布:怎么搭建python环境 编辑:程序博客网 时间:2024/06/04 18:13

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.

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.

基本思想就是将vector数据进行排序,然后去重,最后利用完全背包问题做DP。

#include <iostream>#include <algorithm>#include <vector>#include <cstdio>using namespace std;class Solution {public:    /*    * @param candidates: A list of integers    * @param target: An integer    * @return: A list of lists of integers    */    static vector<vector<int>> combinationSum(vector<int> &candidates, int target) {        // write your code here        std::sort(candidates.begin(), candidates.end());        vector<int>::iterator last_it = std::unique(candidates.begin(), candidates.end());        candidates.resize(std::distance(candidates.begin(), last_it));        vector<vector<int>> result_set;        vector<int> unique_result;        unique_result.reserve(std::distance(candidates.begin(), last_it));        helper(candidates, 0, target, unique_result, result_set);        return result_set;    }    static void helper(vector<int>& arr, int left_num, int target, vector<int>& unique_result, vector<vector<int>>& result_set)    {        if (left_num >= 0 && left_num < arr.size())        {            if (target == 0)            {                result_set.push_back(unique_result);            }            else if (target >= arr[left_num])            {                unique_result.push_back(arr[left_num]);                helper(arr, left_num, target - arr[left_num], unique_result, result_set);                unique_result.pop_back();                helper(arr, left_num + 1, target, unique_result, result_set);            }        }    }};int main(int argc, char * * argv, char * * env){    vector<int> candidates = { 2, 3, 6, 7 };    vector<vector<int>> result_set = Solution::combinationSum(candidates, 7);    for (auto& itvec:result_set)    {        for (auto& it:itvec)        {            cout << it;        }        cout << std::endl;    }    char ch;    scanf_s("%c", &ch);}
原创粉丝点击