for y in maps[c]:
tmp1.append(x+y)
result = tmp1
return result
Solution3. Python3 使用reduce改写
from functools import reduce
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
if len(digits) == 0:
return []
maps = {‘2’:‘abc’,
‘3’:‘def’,
‘4’:‘ghi’,
‘5’:‘jkl’,
‘6’:‘mno’,
‘7’:‘pqrs’,
‘8’:‘tuv’,
‘9’:‘wxyz’
}
return reduce(lambda acc, digit: [x + y for x in acc for y in maps[digit]], digits, [’’])
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
Solution1. C++
class Solution {
public:
vector
vector
permuteHelper(nums, 0, result);
return result;
}
private:
void permuteHelper(vector& nums, int begin, vector
int size = nums.size();
if(begin >= size) {
result.push_back(nums);
return;
}
for(int i = begin; i < size; ++i) {
swap(nums[begin], nums[i]);
permuteHelper(nums, begin+1, result);
swap(nums[begin], nums[i]);
}
}
};
Solution2. Python3
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 0:
return [[]]
return [[num] + p
for i, num in enumerate(nums)
for p in self.permute(nums[:i]+nums[i+1:])]
给定一个二维网格和一个单词,找出该单词是否存在于网格中。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例:
board =
[
[‘A’,‘B’,‘C’,‘E’],
[‘S’,‘F’,‘C’,‘S’],
[‘A’,‘D’,‘E’,‘E’]
]
给定 word = “ABCCED”, 返回 true.
给定 word = “SEE”, 返回 true.
给定 word = “ABCB”, 返回 false.
Solution1. C++
class Solution {
public:
bool exist(vector
if(word.empty()) {
return true;
}
if(board.empty() || board[0].empty()) {
return false;
}
m = board.size();
n = board[0].size();
for (int i=0; i