分金子(360公司2017春招真题)

在这里插入图片描述

递归,时间复杂度过大
在这里插入图片描述

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for(int i = 0; i < T; ++i){
            int n = sc.nextInt();
            int[] a = new int[n];
            for(int j = 0; j < n; ++j){
                a[j] = sc.nextInt();
            }
            int[] res = funCore(a, 0, a.length - 1);
            int A = res[0];
            int B = res[1] - res[0];
            System.out.printf("Case #%d:%d %d\r\n", i + 1, A, B);
        }
    }

    public static int[] funCore(int[] a, int b, int e){
        if(b == e)
            return new int[]{a[b], a[b]};

        int[] l = funCore(a, b, e - 1);
        int[] r = funCore(a, b + 1, e);

        int sum = l[1] + a[e];
        int l_r = Math.min(l[0], r[0]);
        return new int[]{sum - l_r, sum};
    }
}

将递归改程dp矩阵,程序通过。貌似大部分动态规划都是矩阵的时间复杂度低于递归的时间复杂度
在这里插入图片描述
这种情况是因为我System.out.printf()中的冒号后面少了一个空格(下面的代码就是少了一个空格)。加了空格之后就好了
在这里插入图片描述

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt();
        for(int i = 0; i < T; ++i){
            int n = sc.nextInt();
            int[] a = new int[n];
            for(int j = 0; j < n; ++j){
                a[j] = sc.nextInt();
            }
            int[] res = fun(a);
            int A = res[0];
            int B = res[1] - res[0];
            System.out.printf("Case #%d:%d %d\r\n", i + 1, A, B);
        }
    }

    public static int[] fun(int[] a){
        int len_a = a.length;
        int[][][] dp = new int[len_a][len_a][2];

        for(int i = 0; i < len_a; ++i){
            for(int j = 0; j < len_a; ++j){
                int x = j;
                int y = x + i;
                if(y >= len_a)break;
                if(x == y){
                    dp[x][y][0] = a[x];
                    dp[x][y][1] = a[x];
                }else{
                    int sum = dp[x][y - 1][1] + a[y];
                    int min = Math.min(dp[x][y - 1][0], dp[x + 1][y][0]);
                    dp[x][y][0] = sum - min;
                    dp[x][y][1] = sum;
                }
            }
        }
        return dp[0][len_a - 1];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值