題目描述:
給出4個1 - 10的數字,通過加減乘除,得到數字爲24就算勝利
輸入:
4個1 - 10的數字。[數字允許重複,但每個數字僅允許使用一次,測試用例保證無異常數字],通過加減乘除,得到數字爲24就算勝利
輸出:
true or false
思路一:
*整理一下整個運算式子是 num1 o num2 o num3 o num4 (o的地方填運算符)
利用全排列,將四個位置上的數進行組合
o的位置可以是+ - / 任意那麼就是挨個循環出所有的可能性**
代碼:
#include <stdio.h>
#include <algorithm>
using namespace std;
const int N=4;
int num[N];
int isSolve=0;
void dfs(int index,double currentNum,int arr[])
{
if (index >= 4){
if (currentNum == 24)
isSolve = 1;
return;
}
for(int operFlag=0;operFlag<4;operFlag++)
{
switch(operFlag)
{
case 0:
dfs(index+1,currentNum+arr[index],arr);
break;
case 1:
dfs(index+1,currentNum-arr[index],arr);
break;
case 2:
dfs(index+1,currentNum*arr[index],arr);
break;
case 3:
dfs(index+1,currentNum/arr[index],arr);
break;
}
if(isSolve)
return;
}
}
int main()
{
while (cin>>num[0]>>num[1]>>num[2]>>num[3])
{
isSolve = 0;
sort(num, num + 4);
do
{
dfs(1, num[0], num);
if (isSolve)
break;
} while (next_permutation(num, num + 4)); //全排列函數
if (isSolve)
printf("true\n");
else
printf("false\n");
}
return 0;
}
全排列函數介紹:包含頭文件<algorithm>,全排列的數組一定要是有序的,所以使用前一定要排序,否則會只按照當前的大小按字典序逐個增加的排序
使用栗子
對一個數組全排列
#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
int n;
while (scanf("%d", &n) && n){
int a[1000];
for (int i = 0; i<n; i++){
scanf("%d", &a[i]);
}
sort(a, a + n);
do{
for (int i = 0; i<n; i++)
printf("%d ", a[i]);
printf("\n");
} while (next_permutation(a, a + n));
}
return 0;
}
思路二:
開闢一個數組,每次用完一個數據擦掉一個。
一個for循環表示挨個擦去數組中的數據並拿這個數據進行運算;然後用遞歸的形式將這個刪過數據的元素的數組作爲下一輪遞歸的參數,作爲下一輪選取數的數組,直到這個數組中的數全部被取完,就結束。
代碼:
bool CALL(vector<int> v, double res){
if (v.empty()){
return res == 24;
}
for (int i = 0; i<v.size(); i++){
vector<int> tmp(v);
tmp.erase(tmp.begin() + i);
if (CALL(tmp, res + v[i]) || CALL(tmp, res*v[i]) || CALL(tmp, res - v[i]) || CALL(tmp, res / v[i])){
return true;
}
return false;
}
}
int main(){
vector<int> v(4);
while (cin >> v[0]){
for (int i = 1; i<v.size(); i++){
cin >> v[i];
}
if (CALL(v, 0)){
cout << "true" << endl;
}
else
cout << "false" << endl;
}
return 0;
}