2020阿里实习4.22笔试

题目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)));
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值