- leetcode题目
1.1题目描述
1.2知识点及思路
1.3代码 - 总结
一.leetcode题目
1.Factorial Trailing Zeroes
题目描述:给定一个数求其阶乘当中0的个数
知识点:观察找数学规律;二进制移位操作
思路:①找5的倍数②统计出现次数count
代码如下:
class Solution {
public:
int trailingZeroes(int n)
{
int ret=0;
while(n)
{
ret+=n/5;
n=n/5;
}
return ret;
}
};
2.Minimum Depth of Binary Tree
题目描述:求解二叉树的最小深度
知识点:树的基本概念;层次遍历;递归求解
思路:①层次遍历二叉树②遇到左右子树全为空,!temp.first->left&&!temp.first->right,则为最小深度 注:用make_pair做层次结构
参考链接:
http://blog.csdn.net/zziymt/article/details/50708255#comments
http://blog.csdn.net/sbitswc/article/details/26526031
代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root)
{
if(!root)
return 0;
queue<pair<TreeNode*,int>>vec;
vec.push(make_pair(root,1));
while(!vec.empty())
{
pair<TreeNode*,int>temp=vec.front();
vec.pop();
if(!temp.first->left&&!temp.first->right)
return temp.second;
if(temp.first->left)
vec.push(make_pair(temp.first->left,temp.second+1));
if(temp.first->right)
vec.push(make_pair(temp.first->right,temp.second+1));
}
}
};
python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def minDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0
stack,res=[(root,1)],[]
while stack:
p,nDepth=stack.pop()
if not p.left and not p.right:
res.append(nDepth)
if p.right:
stack.append((p.right,nDepth+1))
if p.left:
stack.append((p.left,nDepth+1))
return min(res)
3.Valid Sudoku
题目描述:判断是否为数独
知识点:分治算法
思路:①遍历每行②遍历每列③遍历每个九宫格
知识扩展:回溯法(后面集中讲解)
参考代码如下:
class Solution {
public://链接:hackersun007的修行之路
bool isValidSudoku(vector<vector<char>>& board)
{
// Note: The Solution object is instantiated only once.
vector<vector<bool>> rows(9, vector<bool>(9,false));
vector<vector<bool>> cols(9, vector<bool>(9,false));
vector<vector<bool>> blocks(9, vector<bool>(9,false));
for(int i = 0; i < 9; i++)
for(int j = 0; j < 9; j++)
{
if(board[i][j] == '.')continue;
int num = board[i][j] - '1';
if(rows[i][num] || cols[j][num] || blocks[i - i%3 + j/3][num])
return false;
rows[i][num] = cols[j][num] = blocks[i - i%3 + j/3][num] = true;
}
return true;
}
};
二.总结
I.方法虽同,亦需学习他人优点II.让我们一同努力,明天会更好!