回溯法-数组中和为固定值的组合

在一个非降序排序的数组中,查找和为固定值的所有组合,使用回溯法解决。对于每一个元素有可能在组合中,也有可能不在组合中。

#include<iostream>
#include<vector>
using namespace std;

/************************************************************************/
/* 查找一个非降排序的数组中和为固定值的组合                                                                     */
/************************************************************************/

void Combination_helper(vector<int> array, int begin, int &current, int target, vector<int>&path)
{
    if (begin >= array.size())
        return;
    current += array[begin];
    path.push_back(array[begin]);
    if (current == target)
    {
        for (int i = 0; i < path.size(); i++)
            cout << path[i]<<' ';
        cout << endl;
    }
    Combination_helper(array, begin + 1, current, target, path);
    path.pop_back();
    current -= array[begin];

    int j;
    for (j = begin + 1; j < array.size();)
    {
        if (array[j] == array[begin])
            j++;
        else
            break;
    }
    Combination_helper(array, j, current, target, path);

}
int main()
{
    vector<int>array({1,2,2,3,4,4,5, 5, 6, 6, 7 });
    //vector<int>array({ 1, 2, 3});
    vector<int>path;
    int current = 0;
    Combination_helper(array, 0, current, 10, path);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u012462822/article/details/51193689