🧸🧸🧸各位大佬大家好,我是猪皮兄弟🧸🧸🧸
废话不多说,直接来做题!!
一、📖剪绳子
1.数学方法
class Solution {
public:
int cutRope(int n) {
if(n<=3)
return n-1;
//3 > 1*2
//2 > 1*1
//4 > 1*3 2*2
//5 > 1*4 2*3
//都会用拆分成子绳2,3;
int res=1;
if(n%3==1) res*=4,n-=4;//说明是很多个3+一个4,因为4的绳最大的是4,所以直接减4
else if(n%3==2) res*=2,n-=2;//很多个3+一个5,因为5中有2*3,所以把2处理掉就行
while(n)//处理很多个3
{
res*=3;
n-=3;
}
return res;
}
}
2.DP动态规划
class Solution {
public:
int cutRope(int n) {
//动态规划
if(n<=3) return n-1;
int dp[n+1];
dp[1]=1;
dp[2]=2;
dp[3]=3;
int res=0;//记录最大乘积
for(int i=4;i<=n;i++)
{
for(int j=1;j<=i/2;j++)
res=max(res,dp[j]*dp[i-j]);
dp[i]=res;
}
return dp[n];
}
};
二、📖数值的整数次方
1.直接算
public class Solution {
public double Power(double base, int exponent) {
if(exponent < 0)
{
base = 1 / base;
exponent = -exponent;
//进行负数的处理
}
double res = 1.0;
for(int i = 0; i < exponent; i++)
res *= base;
return res;
}
}
2.快速幂
class Solution {
public:
//快速幂
double Pow(double x, int y){
double res = 1;
while(y){
if(y & 1)
{
res *= x;
}
x *= x;//自己×自己就相当于是二次方倍
y = y >> 1;
}
return res;
}
double Power(double base, int exponent) {
//处理负数次方
if(exponent < 0){
base = 1 / base;
exponent = -exponent;
}
return Pow(base, exponent);
}
};
三、📖树的子结构
利用好短路径特性
class Solution {
bool isSubtree(TreeNode* pRootA, TreeNode* pRootB) {
if (pRootB == NULL) return true;
if (pRootA == NULL) return false;
if (pRootB->val == pRootA->val) {
return isSubtree(pRootA->left, pRootB->left)
&& isSubtree(pRootA->right, pRootB->right);
} else return false;
}
public:
bool HasSubtree(TreeNode* pRootA, TreeNode* pRootB)
{
if (pRootA == NULL || pRootB == NULL) return false;
return isSubtree(pRootA, pRootB) ||
HasSubtree(pRootA->left, pRootB) ||
HasSubtree(pRootA->right, pRootB);
}
};
四、📖牛客oj总结
牛客网是个很不错的刷题软件,也希望大家能天天在上面刷刷题,大厂offer指日可待啊兄弟们。刷起来。