当前位置:网站首页>LeetCode 1981. 最小化目标值与所选元素的差 每日一题
LeetCode 1981. 最小化目标值与所选元素的差 每日一题
2022-07-07 15:32:00 【@小红花】
问题描述
给你一个大小为 m x n 的整数矩阵 mat 和一个整数 target 。
从矩阵的 每一行 中选择一个整数,你的目标是 最小化 所有选中元素之 和 与目标值 target 的 绝对差 。
返回 最小的绝对差 。
a 和 b 两数字的 绝对差 是 a - b 的绝对值。
示例 1:
输入:mat = [[1,2,3],[4,5,6],[7,8,9]], target = 13
输出:0
解释:一种可能的最优选择方案是:
- 第一行选出 1
- 第二行选出 5
- 第三行选出 7
所选元素的和是 13 ,等于目标值,所以绝对差是 0 。
示例 2:输入:mat = [[1],[2],[3]], target = 100
输出:94
解释:唯一一种选择方案是:
- 第一行选出 1
- 第二行选出 2
- 第三行选出 3
所选元素的和是 6 ,绝对差是 94 。
示例 3:输入:mat = [[1,2,9,8,7]], target = 6
输出:1
解释:最优的选择方案是选出第一行的 7 。
绝对差是 1 。
提示:
m == mat.length
n == mat[i].length
1 <= m, n <= 70
1 <= mat[i][j] <= 70
1 <= target <= 800来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/minimize-the-difference-between-target-and-chosen-elements
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
Java
class Solution {
public int minimizeTheDifference(int[][] mat, int target) {
int n = mat.length;
// 70 * 70
boolean[][] dp = new boolean[n][5000];
//处理第一行
for(int num : mat[0]) dp[0][num] = true;
for(int i = 1;i < n;i++){
//每一行的元素
for(int val : mat[i]){
for(int j = val;j < 5000;j++){
//上一行可选j-val值,当前行就可以选j
dp[i][j] = dp[i][j] || dp[i - 1][j - val];
}
}
}
int ans = Integer.MAX_VALUE;
for(int j = 0;j < 5000;j++){
if(dp[n - 1][j]){
ans = Math.min(ans,Math.abs(j - target));
}
}
return ans;
}
}
边栏推荐
- 编程模式-表驱动编程
- The team of East China Normal University proposed the systematic molecular implementation of convolutional neural network with DNA regulation circuit
- Arduino 控制的双足机器人
- 01tire+ chain forward star +dfs+ greedy exercise one
- 1亿单身男女“在线相亲”,撑起130亿IPO
- Tidb cannot start after modifying the configuration file
- [summary of knowledge] summary of notes on using SVN in PHP
- Find tags in prefab in unity editing mode
- 面向接口编程
- 【DesignMode】模板方法模式(Template method pattern)
猜你喜欢
[vulnhub range] thales:1
[Android -- data storage] use SQLite to store data
A tour of gRPC:03 - proto序列化/反序列化
【Vulnhub靶场】THALES:1
3000 words speak through HTTP cache
Statistical learning method -- perceptron
Master this set of refined Android advanced interview questions analysis, oppoandroid interview questions
二叉搜索树(特性篇)
使用JSON.stringify()去实现深拷贝,要小心哦,可能有巨坑
【DesignMode】代理模式(proxy pattern)
随机推荐
模块六
Pisa-Proxy SQL 解析之 Lex & Yacc
php 自带过滤和转义函数
C语言进阶——函数指针
A tour of gRPC:03 - proto序列化/反序列化
The latest interview experience of Android manufacturers in 2022, Android view+handler+binder
Imitate the choice of enterprise wechat conference room
使用JSON.stringify()去实现深拷贝,要小心哦,可能有巨坑
Arduino 控制的双足机器人
【Vulnhub靶场】THALES:1
Three. JS series (2): API structure diagram-2
SqlServer2014+: 创建表的同时创建索引
Usage of config in laravel
1亿单身男女“在线相亲”,撑起130亿IPO
Build an all in one application development platform, light flow, and establish a code free industry benchmark
运算符
预售17.9万,恒驰5能不能火?产品力在线,就看怎么卖
Set the route and optimize the URL in thinkphp3.2.3
spark调优(三):持久化减少二次查询
ATM系统