题目2
给定俩个整数n和m,n能拆分成m个数的和,对于任何一个数字组合不能同时满足以下两个条件:
任取一个数字
1、该数的前一个数比它大
2、该数的后一个数比它大
问题是求出在这样的条件下拆分n的最大组合数。
例如:
输入5 3
输出5
示例解释:
{1,1,3}
{1,2,2}
{1,3,1}
{2,1,2} error不满足
{2,2,1}
{3,1,1}
解决思路:深搜+剪枝,复杂度O((n-m)^m),暂时没想到更快的解法
public class Main {
public static Long ans = 0L;
public static int n = 0;
public static int m = 0;
public static int differ = 0;
public static int allocated = 0;
public void dfs(int[] numberPos, int pos) {
if (pos == numberPos.length) {
return;
}
for (int i = 1; i <= differ; i++) {
numberPos[pos] = i;
allocated += i;
if (allocated > n) {
allocated -= i;
numberPos[pos] -= 1;
return;
}
if (pos > 1 && (numberPos[pos] > numberPos[pos - 1] && numberPos[pos - 1] < numberPos[pos - 2])) {
allocated -= i;
numberPos[pos] -= 1;
return;
}
dfs(numberPos, pos + 1);
if (allocated == n && pos == numberPos.length - 1) {
System.out.println(Arrays.toString(numberPos));
ans++;
}
allocated -= i;
numberPos[pos] -= 1;
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
//正整数n
n = scanner.nextInt();
//分成m个
m = scanner.nextInt();
differ = n - m + 1;
scanner.close();
int[] numberPos = new int[m];
Arrays.fill(numberPos, 1);
Main main = new Main();
main.dfs(numberPos, 0);
System.out.println((long) (ans % (1e109 + 7)));
}
}