思路:
1 牌组里有13张牌,然后想牌组中添加一张牌(1-9)循环10次,看是否能够胡牌,如果添加的这张牌使某个牌超过四张,失败
2 开始回溯算法:必须是递增的有序序列
2.1首先如果当前牌数不是3的倍数,如果至少前两张牌相同,让这两张牌作为一对,剩余牌进行递归,判断能否胡牌
2.2如果当前牌前三张相同,则剩余排序作为新的序列,递归,继续进行判断
2.3如果当前牌能与剩余牌中组成顺子,取出这个顺子,递归,然后剩余牌继续判断。
2.4如果上述情况都不行,则返回false
bool ishu(vector<int>num)
{
if (num.empty())
return true;
int count0 = 0;
//首张牌的个数
count0=count(num.begin(),num.end(),num[0]);
//对应情况2.1
if (num.size() % 3 != 0 && count0 >= 2)
{
vector<int> newnum(num.begin() + 2, num.end());
if (ishu(newnum))
return true;
}
//对应情况2.2
if (count0 >= 3)
{
vector<int> newnum(num.begin() + 3, num.end());
if (ishu(newnum))
return true;
}
//对应情况2.3
if (count(num.begin(), num.end(), num[0] + 1)>0 && count(num.begin(), num.end(), num[0] + 2)>0)
{
vector<int> newnum(num.begin() + 1, num.end());
newnum.erase(find(newnum.begin(), newnum.end(), num[0] + 1));
newnum.erase(find(newnum.begin(), newnum.end(), num[0] + 2));
if (ishu(newnum))
return true;
}
//对应情况2.4
return false;
}
bool hupai(vector<int>num, int n)
{
//牌组中牌数为n的牌已经有4张,则直接false
if (count(num.begin(), num.end(), n) == 4)
return false;
num.push_back(n);
sort(num.begin(), num.end());//有序序列
return ishu(num);
}
int main1()
{
vector<int> num;
vector<int> res;
for (int i = 0; i < 13; ++i)
{
int tmp;
cin >> tmp;
if (tmp > 0 && tmp < 10)
num.push_back(tmp);
else
{
cout << "输入错误" << endl;
return 0;
}
}
for (int n = 1; n < 10; ++n)
{
if (hupai(num, n))
res.push_back(n);
}
if (res.empty())
cout << 0;
else
for (int i = 0; i < res.size(); ++i)
cout << res[i] << " ";
}
京公网安备 11010502036488号