1.將正整數n無序拆分成最大數為m的拆分方案個數,要求所有拆分方案不重復。
樣例:
n = 5, m = 5,對應的拆分方案如下:
5 = 5
5 = 4 + 1
5 = 3 + 2
5 = 3 + 1 + 1
5 = 2 + 2 + 1
5 = 2 + 1 + 1 + 1
5 = 1 + 1 + 1 + 1 + 1
分析:
(1)當n=1,無論m為多少,只有{1}一種划分
(2)當m=1,無論n為多少,只有{1,1,1…}一種划分
(3)當n<m,f(n,m)=f(n,n)
(4)當n=m,如果划分中有n,則只有{n}一種划分;當划分中沒有n,則f(n,n)=f(n,n-1)
f(n,n)= 1 + f(n,n - 1)
(5)當n>m,如果划分中有m,則{m,{x1,x2,…} = n - m},f(n,m)=f(n - m, m);當划分中沒有m,f(n,m)=f(n,m - 1)
f(n,m) = f(n - m, m)+ f(n,m - 1)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
int n = scanner.nextInt();
int m = scanner.nextInt();
int temp = integerhuafen(n, m);
System.out.print(temp);
}
}
public static int integerhuafen(int n, int m) {
int dp[][] = new int[n + 1][m + 1];
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++ ){
if(i == 1 || j == 1){
dp[i][j] = 1;
}else if (i == j) {
dp[i][j] = 1 + dp[i][j - 1];
}else if (i < j) {
dp[i][j] = dp[i][i];
}else {
dp[i][j] = dp[i - j][j] + dp[i][j - 1];
}
}
}
return dp[n][m];
}
}
2.將正整數n拆分成k份,每份不為空,不考慮順序,求划分的種類。
樣例:
n = 7, k = 3;
輸出:
4
{1,1,5; 1,2,4; 1,3,3; 2,2,3}
分析:
(1)分的時候至少有一個1,相當於dp[n][k] = dp[n - 1][k - 1]
(2)分的時候沒有1,dp[n][k] = dp[n - k][k]
=》 dp[n][k] = dp[n - 1][k - 1] + dp[n - k][k]
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner = new Scanner(System.in);
while (scanner.hasNext()){
int n = scanner.nextInt();
int k = scanner.nextInt();
int [][] arr = new int [n + 1][k + 1];
arr[0][0] = 1;
for (int i = 1; i <= n; i++){
for (int j = 1; j <= k; j++){
if(i >= j){
arr[i][j]=arr[i-j][j]+arr[i-1][j-1];
}
}
}
System.out.println(arr[n][k]);
}
scanner.close();
}
}
