Acwing--- 885. Find the number of combinations I (Java)_mathematics_DP analysis to find the number of combinations

Original title link

①. Title

Insert picture description here

②. Thinking

时间复杂度分析

The time complexity of this method of finding the number of combinations is O(n^2), and the maximum n is 2000
Insert picture description here

  • The derivation of this formula is the same as choosing Apple
  • 1. Situation ①: one apple
    is selected, then one apple has been selected at this time, and only b-1 apple is selected from a-1 apples.
  • 2. Situation ②: If this apple is not selected,
    then the situation is obviously to select b apples from the remaining a-1 apples
    Insert picture description here

③. Learning points

组合数模板

④. Code implementation

import java.util.Scanner;

public class Main {
    
    
	static int N=2010,INF=1000000007;
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		int[][] C=new int[N][N];
		for (int a = 0; a <=2000; a++) {
    
    
		//预处理 枚举2000范围内的全部结果
			C[a][0]=1;//初始化从a中挑0个为1
			for (int b =1; b <=a; b++) {
    
    
			//有点dp感觉
				C[a][b]=(C[a-1][b]+C[a-1][b-1])%INF;
			}
		}
		int n=sc.nextInt();
		while(n-->0) {
    
    
			int a=sc.nextInt();
			int b=sc.nextInt();
			System.out.println(C[a][b]);
		}
	}
}

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45480785/article/details/113896568
Recommended