
Implement regular expression matching with support for ‘.’ and ‘*’.
note:
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
######思路:回溯
class Solution {
public:
bool judgePoint24(vector& nums) {
vector cards(nums.size(), 0);
for (int i = 0; i < nums.size(); i++)
cards[i] = (double)nums[i];
return backTracking(cards);
}
bool backTracking(vector& cards) {
if (cards.size() == 0)
return false;
if (cards.size() == 1)
return abs(cards[0] - 24) < 1e-6;
for (int i = 0; i < cards.size(); i++) {
for (int j = 0; j < cards.size(); j++) {
if (i == j)
continue;
vector tempCards;
for (int k = 0; k < cards.size(); k++)
if (k != i && k != j)
tempCards.push_back(cards[k]);
// '+','*','-','/'
for (int k = 0; k < 4; k++) {
if (k < 2 && j < i)
continue;
if (k == 0) tempCards.push_back(cards[i] + cards[j]);
else if (k == 1) tempCards.push_back(cards[i] * cards[j]);
else if (k == 2) tempCards.push_back(cards[i] - cards[j]);
else if (cards[j] == 0) continue;
else tempCards.push_back(cards[i] / cards[j]);
if (backTracking(tempCards))
return true;
tempCards.pop_back();
}
}
}
return false;
}
};




近期评论