趣味算法-巧填运算符

给定一个整数数组,和一个单独的数字,在数组的每一个元素中间填加 "+"或"-" 使其运算结果等於单独的数字例如给定的数组为{7 2 4} ,数字为 9。运算结果为7-2+4=9    


规则1:数组中元素的位置不能变化。

规则2:如果无法实现则输出 Invalid


举例:

Input:

1 2 3 4 10
1 2 3 4 5

Output:

1+2+3+4=10
Invalid


想法:使用穷举法,使用递归在每个位置尝试每个运算符,如果不成立,则需要返回尝试前的状态。


程序示例:(给的测试数字中,最后一个为单独的结果)

#include <iostream>

using namespace std;

void calc(int arr[], int length, int final)
{
    static int index = 0;
    static int sum = arr[0];
    static bool isfind = false, iscomplete = false;
    static char* operators = NULL;

    if (index == 0)
    {
        operators = new char[length];
        memset(operators, '+', length);
    }

    if (isfind)
        return;

    if (index == length-1)
    {
        if (sum == final)
        {
            iscomplete = true;
            isfind = true;

            operators[length-1] = '=';
            for (int i = 0; i < length; i++)
                cout << arr[i] << operators[i]; //ok
            cout << final << endl;
            delete[] operators;
            operators = NULL;
        }
        else
        {
            if (index == 0)
            {
                delete[] operators;
                operators = NULL;
                cout<<"Invalid" << endl;
            }
        }
        return;
    }

    if (!isfind)
    {
        index++;
        sum += arr[index];
        operators[index] = '+';

        calc(arr, length, final);

        if ((!isfind) && (!iscomplete))
        {
            sum -= arr[index];
            operators[index] = '+';
            index--;
        }
    }

    if (!isfind)
    {
        index++;
        sum -= arr[index];
        operators[index] = '-';
        calc(arr, length, final);

        if ((!isfind) && (!iscomplete))
        {
            sum += arr[index];
            operators[index] = '+';
            index--;
        }
    }

    if ((index == 0) && (!isfind))
    {
        delete[] operators;
        operators = NULL;
        cout<<"Invalid" << endl;
    }
}

int main()
{
    //int arr[2] = {3, 3};
    //int arr[2] = {3, 4};
    //int arr[3] = {2, 3, 4};
    int arr[4] = {7, 2, 4, 9};
    //int arr[5] = {1, 2, 3, 4, 10};
    int length = sizeof(arr)/sizeof(arr[0]);

    calc(arr, length-1, arr[length-1]);

    cout<<endl;

    cin >> length;
    return 0;
}


发布了235 篇原创文章 · 获赞 31 · 访问量 59万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章