C语言 | Leetcode C语言题解之第375题猜数字大小II

题目:

题解:

cpp 复制代码
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include <limits.h>

#define MMAX(a, b)        ((a) > (b)? (a) : (b))
#define MMIN(a, b)        ((a) < (b)? (a) : (b))

#define MAX_LEN     1000

int dp[MAX_LEN][MAX_LEN];

//【算法思路】分组DP。
int getMoneyAmount(int n){
    if(n == 1) {
        return 0;
    }

    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            dp[i][j] = 0;
        }
    }

    for(int gap = 0; gap < n; gap++) {
        for(int i = 0; i + gap < n; i++) {
            int j = i + gap;

            if(gap == 0) {
                dp[i][j] = 0;
                continue;
            }

            int min = MMIN(i + 1 + dp[i + 1][j], j + 1 + dp[i][j - 1]);

            for(int k = i + 1; k < j; k++) {
                min = MMIN(min, k + 1 + MMAX(dp[i][k - 1], dp[k + 1][j]));
            }

            dp[i][j] = min;
        }
    }
/*
    for(int i = 0; i < n; i++) {
        for(int j = 0; j < n; j++) {
            printf("dp[%d, %d] = %d     ", i, j, dp[i][j]);
        }
        printf("\n");
    }
*/
    return dp[0][n - 1];
}
相关推荐
爱编码的小八嘎23 分钟前
C语言完美演绎8-4
c语言
@BangBang43 分钟前
leetcode (4): 连通域/岛屿问题
算法·leetcode·深度优先
Mr_pyx1 小时前
【LeetCode Hot 100】 除自身以外数组的乘积(238题)多解法详解
算法·leetcode·职场和发展
故事和你912 小时前
洛谷-数据结构-1-3-集合3
数据结构·c++·算法·leetcode·贪心算法·动态规划·图论
ulias2122 小时前
leetcode热题 - 3
c++·算法·leetcode·职场和发展
菜鸟丁小真3 小时前
LeetCode hot100-287.寻找重复数和994.腐烂的橘子
数据结构·算法·leetcode·知识点总结
零号全栈寒江独钓3 小时前
基于c/c++实现linux/windows跨平台ntp时间戳服务器
linux·c语言·c++·windows
Pentane.4 小时前
【力扣hot100】【Leetcode 15】三数之和|暴力枚举 双指针 算法笔记及打卡(14/100)
数据结构·笔记·算法·leetcode
我能坚持多久5 小时前
String类常用接口的实现
c语言·开发语言·c++
CPUOS20105 小时前
嵌入式C语言高级编程之单一职责原则
c语言·开发语言·单一职责原则