计蒜客-24点游戏 DFS

计蒜客-24点游戏 DFS

题目链接 https://www.jisuanke.com/course/709/36566

说明:题目有错,应该是2,3,4,5,6,7,8,9,10...少了个10

题解:DFS搜索即可。因为每种牌有4种花色,所以看作是有52种不同类型的牌,直接一个数组将52种牌给列出来,从左到右DFS扫描,每张牌2种选择:选或者不选。搜索完判断下累积和是否是24即可。注意中途剪下枝,以缩短程序运行时间。

还有个就是,如果想检查结果是否正确,每次累计24点的时候输出选择的所有数,但是这样程序运行时间会大大增加。

 

#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
using namespace std;
typedef long long ll;
int a[] = {1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,6,6,6,6,7,7,7,7,8,8,
8,8,9,9,9,9,10,10,10,10,11,11,11,11,12,12,12,12,13,13,13,13};
int len = 4*13;
ll res = 0;
vector<int> vec;
//void Put() {
//	int len = vec.size();
//	for(int i = 0;i < len;i++) {		
//		printf("%d%s",vec[i],i==len-1?"\n":" ");
//	}
//}
void DFS(int pos,int cnt) {
	
	if(cnt > 24) return;
	if(pos == len) {
		if(cnt==24)	 {
			res++;
		//	Put();			
		//	getchar();
		}
		return;
	}
	//if(a[pos]+cnt >24) return;
	// 选pos	
	//vec.push_back(a[pos]);
	DFS(pos+1,cnt+a[pos]);
	//vec.pop_back();
	// 不选pos 
	DFS(pos+1,cnt);
}

int main() {
	
	DFS(0,0);
	printf("%lld\n",res);
	return 0;
}