暴力解决,超时…
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; // 回溯
}
}
}