給定一個整數數組,和一個單獨的數字,在數組的每一個元素中間填加 "+"或"-" 使其運算結果等於單獨的數字例如給定的數組爲{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;
}