2020 Ali practice written test - playing cards -DFS
Title Description
Today Xiaoqiang to come from a deck of cards in a stack, including A, 2,3, ..., 10 each of the four in which A represents 1. He pulled out some of the cards in a stack to Xiao Ming From this and tell each Xiaoming Some cards can be played in the following way:
- Single cards: a card, such as 3
- Pair: two cards of the same figure, for example, 77
- Straight: Five cards of consecutive numbers, such as A2345
- Three pairs: three consecutive pairs: for example, 334,455
now Xiaoqiang want to know how many times you can play cards at least polish their hand.
Enter a description:
Line is a space-separated integers A . 1 , A 2 , ... A 10 , representing the card is A, 2, ..., the number 10.
0 <= A . 1 , A 2 , ..., A 10 <=. 4
guarantee hand At least one card
Output Description:
Only one per line integer answer
Example:
Input:
1 1 1 2 2 2 2 2 1 1
Export
3
Description:
Hit three straight, are: A2345,45678,678910
Depth-first Code:
public class Main {
public static int min = Integer.MAX_VALUE;
public static boolean check(int[] nums) {
boolean flag = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] > 0) {
flag = true;
break;
}
}
return flag;
}
public static void dfs(int[] nums, int count) {
//剪枝
if(count>min)
{
return;
}
if (check(nums)) {
int i = 0;
while (nums[i] == 0) {
i++;
}
//单张
if (nums[i] > 0) {
nums[i]--;
dfs(nums, count+1);
nums[i]++;
}
//对子
if (nums[i] > 1) {
nums[i] -= 2;
dfs(nums,count+1);
nums[i] += 2;
}
//五连
if (i + 5 <= nums.length && nums[i] > 0 && nums[i + 1] > 0 && nums[i + 2] > 0 && nums[i + 3] > 0 && nums[i + 4] > 0) {
for (int j = 0; j < 5; j++) {
nums[i + j]--;
}
dfs(nums, count+1);
for (int j = 0; j < 5; j++) {
nums[i + j]++;
}
}
//三双
if (i + 3 <= nums.length && nums[i] > 1 && nums[i + 1] > 1 && nums[i + 2] > 1) {
nums[i] -= 2;
nums[i + 1] -= 2;
nums[i + 2] -= 2;
dfs(nums, count+1);
nums[i] += 2;
nums[i + 1] += 2;
nums[i + 2] += 2;
}
} else {
if(count<min)
{
min = count;
}
}
}
public static void main(String[] args) {
int[] nums = new int[]{1, 1, 1, 2, 2, 2, 2, 2, 1, 1};
dfs(nums, 0);
System.out.println(min);
}
}