[C++ ] 24點遊戲算法


例題描述

問題描述:給出41-10的數字,通過加減乘除,得到數字爲24就算勝利

  • 輸入描述:
    輸入4int整數(數字允許重複,但每個數字僅允許使用一次,測試用例保證無異常數字)

  • 輸出描述:
    返回能否得到24點,true or false

示例1:

  • 輸入:
    7 2 1 10
  • 輸出:
    true

解題思路

深度優先搜索,先排序,再進行全排列(利用算法中的全排列函數next_permutation),然後使用遞歸考慮所有的加、減、乘、除操作。


代碼實現

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 4;
int num[N];
int isSolve = 0;

void dfs(int index, int currentNum, int arr[]){
	if (currentNum == 24){
		isSolve = 1;
		return;
	}
	if (isSolve || currentNum > 24 || index >= 4)
		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)
			cout << "true" << endl;
		else
			cout << "false" << endl;
	}
	return 0;
}

鏈接:https://www.nowcoder.com/questionTerminal/fbc417f314f745b1978fc751a54ac8cb?orderByHotValue=1&pos=9&questionTypes=000100

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章