153. Number Combination II

153. Number Combination II
 

Given an array num and an integer target. Find the combination where the sum of all the numbers in num is the target.
Example

Example 1:

Input: num = [7,1,2,5,1,6,10], target = 8
Output: [[1,1,6],[1,2,5],[1,7],[2 ,6]]

Example 2:

Input: num = [1,1,1], target = 2
Output: [[1,1]]
Explanation: The solution set cannot contain repeated combinations

Precautions

    In the same combination, each number in num can only be used once.
    All values ​​(including target) are positive integers.
    The numbers in each combination returned must be in non-descending order.
    All combinations returned can be any combination Sequence. The
    solution set cannot contain repeated combinations.

vector<vector<int>> combinationSum2(vector<int> &num, int target)
{
    set<vector<int>> retSet;

    int len = num.size();
    vector<int> tmpSet;
    std::multimap<int, vector<int>> tmpMap; //sum vector
    vector<int> tmpSet2;
    for (int i = 0; i < len; i++)
    {
        if (num[i] == target)
        {
            tmpSet2.clear();
            tmpSet2.push_back(num[i]);
            retSet.insert(tmpSet2);
            continue;
        }

        if (num[i] > target)
        {
            continue;
        }


        std::multimap<int, vector<int>> tmpMap2 = tmpMap;
        for (auto itMap : tmpMap2)
        {
            for (auto itSet : itMap.second)
            {
                if (itMap.first + num[i] == target)
                {
                    tmpSet2.clear();
                    tmpSet2 = itMap.second;
                    tmpSet2.push_back(num[i]);
                    sort(tmpSet2.begin(), tmpSet2.end());
                    retSet.insert(tmpSet2);
                }
                else if (itMap.first + num[i] < target)
                {
                    tmpSet2.clear();
                    tmpSet2 = itMap.second;
                    tmpSet2.push_back(num[i]);
                    tmpMap.insert(std::pair<int, vector<int>>(itMap.first + num[i], tmpSet2));
                }
            }
        }
        tmpSet2.clear();
        tmpSet2.push_back(num[i]);
        tmpMap.insert(std::pair<int, vector<int>>(num[i], tmpSet2));
    }

    vector<vector<int>>retVec;
    for (auto it : retSet)
    {
        vector<int>tmpVec;
        for (auto itt : it)
        {
            tmpVec.push_back(itt);
        }
        retVec.push_back(tmpVec);
    }
    
    return retVec;
}
void test()
{
    /*vector<int> num = { 7,1,2,5,1,6,10 };
    int target = 8;*/  
    /*vector<int> num = { 29, 19, 14, 33, 11, 5, 9, 23, 23, 33, 12, 9, 25, 25, 12, 21, 14, 11, 20, 30, 17, 19, 5, 6, 6, 5, 5, 11, 12, 25, 31, 28, 31, 33, 27, 7, 33, 31, 17, 13, 21, 24, 17, 12, 6, 16, 20, 16, 22, 5 };
    int target = 28;*/

    vector<int> num = { 2, 2, 2 };
    int target = 2;

    vector<vector<int>> ret = combinationSum2(num,  target);
}

 

 

Guess you like

Origin blog.csdn.net/yinhua405/article/details/110421000