写了一小时,具体思路如下:
确定下一张牌是哪张,for:1->9,构建出card数组表示每一张牌的数量,card[i]>4,直接跳过
确定雀头是哪一张:for:1->9,card[i]-=2;
剩下的牌组成顺子或者刻子,显然1张或者2张必定组成顺子,于是从小到大开始组牌,先从小到大去除顺子
当第i牌的前一张牌的数量为0,或者i==0,那么必定有一个顺子是以i开头,于是可以找出顺子,
如果不能组成顺子,那么只能组成刻子,这里要考虑4张了,4一张一般由一个刻子和一个顺子组成。具体代码:
package org.niuke.soltion65;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class Main {
/**
* @param card 每张牌的数量
* @return 是否能够胡牌
*/
public static boolean just(int[] card){
for(int i = 0; i < card.length; i++){
int cnt = 14;
if(card[i] >= 2){
int[] temp = Arrays.copyOf(card, 9);
temp[i] -= 2;//雀头(对子)
cnt -= 2;
//去除以 index为头的顺子,例如:3个1,以1作为雀头,这个1必定要组成顺子的。
for(int k = 0; k < temp.length; k++){
if((k == 0 || temp[k - 1] == 0) && (temp[k] == 1 || temp[k] == 2)){ //只有1张或者两张必定组成顺子
if(removeABC(temp, k)){
cnt -= 3;
if(temp[k] == 1){
if(removeABC(temp, k)){
cnt -= 3;
}else{
break;
}
}
}else{
break;
}
}
//去除刻子
if(removeAAA(temp, k)){
cnt -= 3;
if(temp[k] == 1){
if(removeABC(temp, k)){
cnt -= 3;
}else{
break;
}
}
}
}
if(cnt == 0){
return true;
}
}
}
return false;
}
//去除一个从index开始的顺子
public static boolean removeABC(int[] card, int index){
if(index >= 0 && index + 2 < card.length && card[index] >= 1 && card[index + 1] >= 1 && card[index + 2] >= 1){
card[index]--;
card[index + 1]--;
card[index + 2]--;
return true;
}
return false;
}
//去除一个index+1的刻子
public static boolean removeAAA(int[] card, int index){
if(index >= 0 && index < card.length && card[index] >= 3){
card[index] -= 3;
return true;
}
return false;
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
int[] input = Arrays.stream(scanner.nextLine().split(" "))
.mapToInt(Integer::parseInt).toArray();
int[] card = new int[9];
for(int i = 0; i < input.length; i++){
card[input[i] - 1] += 1;
}
ArrayList<Integer> arr = new ArrayList<>();
for(int i = 0; i < card.length; i++){
int[] cardCopy = Arrays.copyOf(card, 9);
cardCopy[i]++;
if(cardCopy[i] <= 4 && just(cardCopy)){
arr.add(i + 1);
}
}
if(arr.isEmpty()){
System.out.println("0");
}else{
for(int i = 0; i < arr.size() - 1; i++){
System.out.print(arr.get(i) + " ");
}
System.out.println(arr.get(arr.size() - 1));
}
}
}

京公网安备 11010502036488号