1.整数转罗马数字
python:
class Solution:
def intToRoman(self, num: int) -> str:
dict_ = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'}
res = ''
for key in dict_:
count = num // key
res += count * dict_[key]
num %= key
return res
c++:?
class Solution {
public:
string intToRoman(int num) {
int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
string str_[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
string res;
for(int i = 0; i < 13; i++){
while(num >= value[i]){
num -= value[i];
res += str_[i];
}
}
return res;
}
};
2.电话号码的字母组合?
?python:
class Solution:
def help(self, digits, track):
if len(digits)==0:
self.res.append(''.join(track))
return
for letter in self.dict_[digits[0]]:
# store = track.copy()
track.append(letter)
self.help(digits[1:], track)
# track.pop()
track = store
def letterCombinations(self, digits: str) -> List[str]:
if len(digits)==0:
return []
self.dict_={"2":"abc","3":"def","4":"ghi","5":"jkl","6":"mno","7":"pqrs","8":"tuv","9":"wxyz"}
self.res = []
self.help(digits, [])
return self.res
c++:
class Solution {
public:
vector<string> res;
// unordered_map<char, string> phoneMap;
void help(string digits, vector<char> track, unordered_map<char, string> phoneMap){
if(digits.empty()){
string str(track.begin(), track.end());
res.push_back(str);
}
for(int i=0; i < phoneMap[digits[0]].size(); i++){
track.push_back(phoneMap[digits[0]][i]);
help(digits.substr(1, digits.size() - 1), track, phoneMap);
track.pop_back();
}
}
vector<string> letterCombinations(string digits) {
if (digits.empty()) {
return res;
}
unordered_map<char, string> phoneMap{
{'2', "abc"},
{'3', "def"},
{'4', "ghi"},
{'5', "jkl"},
{'6', "mno"},
{'7', "pqrs"},
{'8', "tuv"},
{'9', "wxyz"}
};
vector<char> track;
help(digits, track, phoneMap);
return res;
}
};
|