新农上路
- 积分
- 99
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2012-6-2
- 最后登录
- 1970-1-1
|
第四题我的想法是,可以用hashmap记录所有可能的顺子,triple和对子,针对每一张牌,依次尝试去匹配顺子,triple和对子。
对于follow up,根据纸牌的数量N,可以算出顺子和triple的数量,因为只有一个对子。
下面是实现的代码,没有编译和测试,直接在google docs上写的。
- constexpr int kCardNum = 14;
- constexpr int kPairNum = 1;
- constexpr int kStraightAndTripleNum = (kCardNum - 2) / 3;
- bool canWin(vector<int>& cards) {
- if (cards.size() != kCardNum) {
- return false;
- }
- unordered_map<int, unordered_set<int>>& straights;
- unordered_map<int, int>& triples,
- unordered_map<int, int>& pairs;
- return canWin(0, cards, straights, triples, pairs);
- }
- bool canWin(int index, const vector<int>& cards,
- unordered_map<int, unordered_set<int>>& straights,
- unordered_map<int, int>& triples,
- unordered_map<int, int>& pairs) {
- if (index == cards.size()) {
- return validate(straights, triples, pairs);
- }
- // try to form a straight
- int currNum = cards[index];
- for (int next = currNum; next >= max(1, currNum - 2); --next) {
- auto& straight = straights[next];
- if (straight.find(currNum) == straight.end()) {
- straight.insert(currNum);
- if (canWin(index + 1, cards, straights, triples, pairs)) {
- return true;
- }
- straight.erase(currNum);
- }
- }
- // try to form a triple
- if (triples[num] < 3) {
- triples[num]++;
- if (canWin(index + 1, cards, straights, triples, pairs)) {
- return true;
- }
- triples[num]--;
- }
- // try to form a pair
- if (pairs[num] < 2) {
- pairs[num]++;
- if (canWin(index + 1, cards, straights, triples, pairs)) {
- return true;
- }
- pairs[num]--;
- }
- return false;
- }
- bool validate(unordered_map<int, unordered_set<int>>& straights,
- unordered_map<int, int>& triples,
- unordered_map<int, int>& pairs) {
- int numStraight = 0, numTriple = 0, numPair = 0;
- for (const auto& entry : straights) {
- if (entry.second.size() == 3) {
- ++numStright;
- }
- }
- for (const auto& entry : triples) {
- if (entry.second == 3) {
- ++numTriple;
- }
- }
- for (const auto& entry : pairs) {
- if (entry.second == 2) {
- ++numPair;
- }
- }
- if (numStraight + numTriple == 4 && numPair == 1) {
- return true;
- }
- return false;
- }
复制代码 |
|