2021-2-26第六届蓝桥杯javaB组-牌型种数

暴力解决,超时…

public class Main {
	public static void main(String[] args) {
		int ans = 0;
		for (int n1 = 0; n1 <= 4; n1++) {
			for (int n2 = 0; n2 <= 4; n2++) {
				for (int n3 = 0; n3 <= 4; n3++) {
					for (int n4 = 0; n4 <= 4; n4++) {
						for (int n5 = 0; n5 <= 4; n5++) {
							for (int n6 = 0; n6 <= 4; n6++) {
								for (int n7 = 0; n7 <= 4; n7++) {
									for (int n8 = 0; n8 <= 4; n8++) {
										for (int n9 = 0; n9 <= 4; n9++) {
											for (int n10 = 0; n10 <= 4; n10++) {
												for (int n11 = 0; n11 <= 4; n11++) {
													for (int n12 = 0; n12 <= 4; n12++) {
														for (int n13 = 0; n13 <= 4; n13++) {
															int pai = n1 + n2 + n3 + n4 + n5 + n6 + n7 + n8 + n9 + n10 + n11 + n12 + n13;
															if (pai == 13) {
																ans++;
															}
														}
													}
												}
											}
										}
									}
								}
							}
						}
					}
				}
			}
		}
		System.out.println(ans);
	}
}


递归


public class Main {

	static int ans = 0;

	public static void main(String[] args) {
		GetResult(0, 0);
		System.out.println(ans);
	}

	public static void GetResult(int type, int count) {
		if (count == 13 || type > 13) {
			if (type == 13) {
				ans++;
			}
		} else {
			for (int i = 0; i <= 4; i++) {
				GetResult(type + i, count + 1);
			}
		}
	}
}


深度搜索

递归回溯算法模板

public class Main {
	static int k[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 };
	static int ans = 0;

	public static void main(String args[]) {
		int t[] = new int[14];      // 记录每个牌已经拿了几张
		GetResult(0, 0, t);         // 每一张可以拿0,1,2,3,4张, 第一个0代表1~13中的第一张的点数 ,第二个0代表拿到的总数
		System.out.println(ans);    // 输出结果
	}

	public static void GetResult(int q, int w, int t[]) {
		if (w == 13) {              // 牌数够了,就++,退出循环
			ans++;
			return;
		}
		if (q == 13) return;        // 已经拿了最后点数为13的牌了,因为是从牌为1开始计算的
		for (int i = 0; i <= 4; i++) {
			w += i;                 // 牌数的增加
			t[q] = i;               // 记录每种牌数拿了几张
			GetResult(q + 1, w, t); // 深度优先搜索
			w -= i;                 // 回溯
		}
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值