1 Star 1 Fork 0

laodasbch/Leetcode-Complete-Guide

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
1569.txt 2.42 KB
一键复制 编辑 原始数据 按行查看 历史
JunB(66哥) 提交于 5年前 . Create 1569.txt
思路:
树状dp + 组合数学
import java.math.BigInteger;
class Solution {
BigInteger fact[];
BigInteger dp[];
int MOD=1000000007;
int cntdp[];
Map<Integer,TreeNode>map=new HashMap<>();
public int numOfWays(int[] A) {
fact=new BigInteger[A.length+1];
dp=new BigInteger[A.length+1];
cntdp=new int[A.length+1];
fact[0]=BigInteger.ONE;
fact[1]=BigInteger.ONE;
for(int i=2;i<A.length+1;i++){
fact[i]=fact[i-1].multiply(BigInteger.valueOf(i));
}
TreeNode root=new TreeNode(A[0]);
for(int i=1;i<A.length;i++){
build(root,A[i]);
}
post(root);
return (int)(dfs(root).mod(BigInteger.valueOf(MOD)).longValue()-1);
}
public BigInteger dfs(TreeNode root){
if(root==null)return BigInteger.ONE;
if(dp[root.val]!=null)return dp[root.val];
BigInteger res=BigInteger.ONE;
int lcnt=0,rcnt=0;
if(root.left!=null){
lcnt=cntdp[root.left.val];
}
if(root.right!=null){
rcnt=cntdp[root.right.val];
}
if(lcnt==0&&rcnt==0)return BigInteger.ONE;//itself
BigInteger left=dfs(root.left);
BigInteger right=dfs(root.right);
BigInteger a=res.multiply(left).multiply(right).multiply(F(lcnt+rcnt)).divide(F(lcnt)).divide(F(rcnt));
BigInteger b=a.mod(BigInteger.valueOf(MOD));
dp[root.val]=b;
return b;
}
public BigInteger F(int i){
return fact[i];
}
class TreeNode{
int val=0;
TreeNode left;
TreeNode right;
public TreeNode(int val){
this.val=val;
}
}
public void build(TreeNode root,int v){
if(v>root.val){
if(root.right==null){
root.right=new TreeNode(v);
return;
}else{
build(root.right,v);
}
}else{
if(root.left==null){
root.left=new TreeNode(v);
return;
}else{
build(root.left,v);
}
}
}
public int post(TreeNode root){
if(root==null)return 0;
int l=post(root.left);
int r=post(root.right);
cntdp[root.val]=1+l+r;
return cntdp[root.val];
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/laodasbch/Leetcode-Complete-Guide.git
git@gitee.com:laodasbch/Leetcode-Complete-Guide.git
laodasbch
Leetcode-Complete-Guide
Leetcode-Complete-Guide
master

搜索帮助