时间限制:1秒
空间限制:32768K
热度指数:139492
算法知识视频讲解
题目描述
我们可以用2*1的小矩形横着或者竖着去覆盖更大的矩形。请问用n个2*1的小矩形无重叠地覆盖一个2*n的大矩形,总共有多少种方法?
思路:典型的斐波那契数列
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int rectCover(int number) {
if(number <= 2) return number;
return rectCover(number-1)+rectCover(number-2);
}
};
时间限制:1秒
空间限制:32768K
热度指数:204418
算法知识视频讲解
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
#include <bits/stdc++.h>
using namespace std;
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
{
if(!pRoot1) return false;/*空树不是任意一个树的子结构*/
if(!pRoot2) return false;/*空树不是任意一个树的子结构*/
return (dfs(pRoot1,pRoot2)||HasSubtree(pRoot1->left,pRoot2)||HasSubtree(pRoot1->right,pRoot2));
}
bool dfs(TreeNode* r1, TreeNode* r2)
{
if(!r2) return true;/*如果B二叉树的节点都已经匹配完了,那么符合条件*/
if(!r1) return false;
if(r1->val != r2->val) return false;
return (dfs(r1->left,r2->left)&&dfs(r1->right,r2->right));
}
};
时间限制:1秒
空间限制:32768K
热度指数:121779
算法知识视频讲解
题目描述
操作给定的二叉树,将其变换为源二叉树的镜像。
输入描述:
二叉树的镜像定义:源二叉树 8 / \ 6 10 / \ / \ 5 7 9 11 镜像二叉树 8 / \ 10 6 / \ / \ 11 9 7 5
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
void Mirror(TreeNode *pRoot) {
if(!pRoot) return;
TreeNode* p;
p=pRoot->left;
pRoot->left = pRoot->right;
pRoot->right = p;
Mirror(pRoot->left);
Mirror(pRoot->right);
}
};
时间限制:1秒
空间限制:32768K
热度指数:90361
算法知识视频讲解
题目描述
在一个长度为n的数组里的所有数字都在0到n-1的范围内。 数组中某些数字是重复的,但不知道有几个数字是重复的。也不知道每个数字重复几次。请找出数组中任意一个重复的数字。 例如,如果输入长度为7的数组{2,3,1,0,2,5,3},那么对应的输出是第一个重复的数字2。
class Solution {
public:
// Parameters:
// numbers: an array of integers
// length: the length of array numbers
// duplication: (Output) the duplicated number in the array number
// Return value: true if the input is valid, and there are some duplications in the array number
// otherwise false
bool duplicate(int numbers[], int length, int* duplication) {
map<int,int> mp;
if(length<=1||numbers==NULL) return false;
int cnt=0;
for(int i=0;i<length;i++)
{
mp[numbers[i]]++;
if(mp[numbers[i]]>1)
{
duplication[cnt++]=numbers[i];
return true;
}
}
return false;
}
};
时间限制:1秒
空间限制:32768K
热度指数:124096
算法知识视频讲解
题目描述
在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置
class Solution {
public:
int FirstNotRepeatingChar(string str) {
if(str.size()==0) return -1;
int hash[255]={0};
int len = str.length();
for(int i=0;i<len;i++)
hash[str[i]-'A']++;
for(int i=0;i<len;i++)
{
if(hash[str[i]-'A']==1)
return i;
}
return 0;
}
};