[Linear dp] C000_ Put Apple

1. Title Description

Put M identical apples in N identical plates, and allow some plates to be left empty. How many different points are there? (Indicated by K) 5,1,1 and 1,5,1 are the same division method.

Input

The first line is the number of test data t (0 <= t <= 20). Each line below contains two integers M and N, separated by spaces. 1 <= M, N <= 10.

Output

For each set of input data M and N, use a line to output the corresponding K.

样例输入
1
7 3
样例输出
8

Second, the solution

Method One: Random Search

Let a be the number of apples and b be the number of baskets, as listed below:

  • a = 1 || b == 1 Time:
    • Put the only apple in a basket.
    • Or put all the apples in the only basket.
  • b > a At that time, there must be ba baskets that are empty. These baskets do not affect my choice of placement, because I can only let a basket have apples.
  • b <= a When it can be divided into two situations:
    • a = b When, in fact, there are very many options:
      • Let the basket empty: But in order to be sparse and not miss, I only leave one basket at most at a time.
      • Keep the baskets empty: or each basket is full.
    • b < a There are also two options:
      • Let the basket empty: But in order to be sparse and not miss, I only leave one basket at most at a time.
      • Let the basket not be empty, let b baskets have one apple each, and the remaining ab apples make other plans.
import java.util.*;
import java.math.*;
import java.io.*;
public class Main{
	static boolean[] vis;
	static int res;
	
	private static int dfs(int a, int b) {
		if (a == 1 || b == 1)
			return 1;
		if (a == b) 
			return dfs(a, b-1) + 1;
		if (a < b)
			return dfs(a, a);
		if (a > b)
			return dfs(a, b-1) + dfs(a-b, b);
	}
    public static void main(String[] args) throws IOException {  
        Scanner sc = new Scanner(new BufferedInputStream(System.in));
        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
		
		int t = sc.nextInt();
		while (t-- > 0) {
			int a = sc.nextInt();	//app
			int b = sc.nextInt();	//篮子
			System.out.println(dfs(a, b));
		}
    }
}

Complexity analysis

  • time complexity: O ( ) O()
  • Space complexity: O ( ) O()

Method 2: dp

Charge d'affaires ...


Complexity analysis

  • time complexity: O ( ) O()
  • Space complexity: O ( ) O()
Published 714 original articles · praised 199 · 50,000+ views

Guess you like

Origin blog.csdn.net/qq_43539599/article/details/105619242