代码拉取完成,页面将自动刷新
思路:
树状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];
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。