LeetCode——Dynamic Planning (2)

 The order and ideas for answering questions come from Code Caprice, website address: https://programmercarl.com 

343. Integer split - LeetCode

Given a positive integer  n , split it into  k the   sum of  positive integersk >= 2 (  ) and maximize the product of these integers.

Returns  the largest product you can get  .

输入: n = 2
输出: 1
解释: 2 = 1 + 1, 1 × 1 = 1。
import java.util.Scanner;

/**
 * @author light
 * @Description 整数拆分
 * @create 2023-09-14 18:19
 */
public class IntegerBreakTest {
	public static void main(String[] args) {
		Scanner input=new Scanner(System.in);
		int n=input.nextInt();
		System.out.println(integerBreak(n));
	}
	public static int integerBreak(int n) {
		 //dp[i] 为正整数 i 拆分后的结果的最大乘积
        int[] dp = new int[n+1];
        dp[2] = 1;
        for(int i = 3; i <= n; i++) {
            for(int j = 1; j <= i-j; j++) {
                // 这里的 j 其实最大值为 i-j,再大只不过是重复而已,
                //并且,在本题中,我们分析 dp[0], dp[1]都是无意义的,
                //j 最大到 i-j,就不会用到 dp[0]与dp[1]
                dp[i] = Math.max(dp[i], Math.max(j*(i-j), j*dp[i-j]));
                // j * (i - j) 是单纯的把整数 i 拆分为两个数 也就是 i,i-j ,再相乘
                //而j * dp[i - j]是将 i 拆分成两个以及两个以上的个数,再相乘。
            }
        }
        return dp[n];
	}
}

96. Different binary search trees - LeetCode

Given an integer  ,  how many binary search treesn are  there that consist of exactly  n n nodes and whose node values   ​​are different  from 1 to  ? Returns the number of binary search trees that satisfy the question.n

 


/**
 * @author light
 * @Description 不同的二叉搜索树
 *
 * @create 2023-09-14 18:49
 */
public class NumTreesTest {
	public int numTrees(int n) {
		//1 确认dp数组及其含义:dp[i]:输入【i】,共有dp[i]种不同的二叉搜索树
		//也可以理解是i个不同元素节点组成的二叉搜索树的个数为dp[i] ,都是一样的。
		//dp[i] += dp[以j为头结点左子树节点数量] * dp[以j为头结点右子树节点数量]
		//j相当于是头结点的元素,从1遍历到i为止。
		int[] dp=new int[n+1];
		dp[0]=1;
		for (int i = 1; i <=n; i++) {
			for (int j = 1; j <=i; j++) {
				dp[i]+=dp[j-1]*dp[i-j];
			}
		}
		return dp[n];
	}
}

Guess you like

Origin blog.csdn.net/zssxcj/article/details/132888099