当前位置:网站首页>leetcode:1755. Sum of subsequences closest to the target value
leetcode:1755. Sum of subsequences closest to the target value
2022-07-05 21:04:00 【Oceanstar's study notes】
Title source
Title Description


class Solution {
public:
int minAbsDifference(vector<int>& nums, int goal) {
}
};
title
Analyze the amount of data
Before looking at the question , Let's first look at the amount of data given : 1 < = n u m s . l e n g t h < = 40 1 <= nums.length <= 40 1<=nums.length<=40, It means :
- One side , It is almost impossible to have O ( N 2 ) 、 O ( N 2 l o g N ) 、 O ( N 3 ) O(N^2)、O(N^2 logN)、O(N^3) O(N2)、O(N2logN)、O(N3), Such time complexity , because [1,40] The data range of is too small
- On the other hand , It can't have O ( 2 N ) 、 O ( N ∗ 2 N ) 、 O ( 3 N ) O(2^N)、O(N * 2^N)、O(3^N) O(2N)、O(N∗2N)、O(3N) Such time complexity , because [1,40] The data range of is too large
In general , Data volume n < = 20 n <= 20 n<=20, This implies that we should use a Exponential level algorithm To solve , For example, divide and conquer 、 to flash back 、dfs etc. , Like what dynamic planning and so on pass. So for n < = 40 n <= 40 n<=40, The only possibility is to 40 Split into two 20, Then run an exponential complexity solution on both sides
Then look at the data range , It seems a little big , Dynamic programming pass
Analyze the meaning of the question
Then come to the question . The title requires us to select some subsets from the array , the sum( A subset of ) Recently, I received goal.
Because the requirements are the closest , So we definitely need to look at all subsets .
Enumerating all subsets can be done by backtracking .
But because of the amount of data n < = 40 n <= 40 n<=40, If you enumerate all subsets, the complexity is 2 4 0 2^40 240, It's bound to time out , So we need to deal with it
Add
ps: About “ The sum of subsequences closest to the target value ” This kind of question :
- If the array length is particularly large , But the value is small , We can solve the knapsack problem
- But if the array length is not big , But if the value is particularly large , Use DFS.
dfs

class Solution {
int point = 0; // Pointer to array data combination ( Indicates the subscript of an array )
/** * @param nums The array given by the title * @param start The starting position of the array * @param end The end position of the array * @param sum Save the left combined sum (sum) * @param arr Save the sum of the array combination */
void dfs(vector<int>& nums, int goal, int start, int sum, vector<int>& arr){
arr[point++] = sum;
for (int i = start; i < nums.size(); ++i) {
dfs(nums, goal, i + 1, sum + nums[i], arr);
}
}
public:
int minAbsDifference(vector<int>& nums, int goal) {
int N = nums.size();
int mid = N >> 1;
point = 0;
// data { 5, -7, 3, 5 }==> left [5,-7] On the right side [5,-2]
// Save the combination of all data on the left ==>[0, -7, 5, -2] The data on the left is (5,-7)
std::vector<int> l(1 << 20);
// Save the combination of all data on the right ==>[0, 5, 3, 8] The data on the right is (5,-2)
std::vector<int> r(1 << 20);
dfs(nums, 0, mid - 1, 0, l); // Enumerate all combinations on the left
point = 0;// Pointer return 0
dfs(nums, mid, N - 1, 0, r);// Enumerate all combinations on the right
int ans = INT32_MAX;
std::sort(l.begin(), l.end());
std::sort(r.begin(), r.end());
// Combine left data with right data
int left = 0, right = N - 1;
for(int x : l){
ans = std::min(ans, std::abs(goal - x));
}
for(int x : r){
ans = std::min(ans, std::abs(goal - x));
}
while (left < N && right >= 0){
int t = l[left] + r[right]; // Temporarily save the combination of left data and right data
ans = std::min(ans, std::abs(t - goal));
if(t > goal){
right--;
}else{
left++;
}
}
return ans;
}
};
violence ( Overtime )
Enumerate all subsequences
class Solution {
int ans = INT32_MAX;
void dfs(vector<int>& nums, int goal, int start, int sum){
ans = std::min(ans, std::abs(sum - goal));
for (int i = start; i < nums.size(); ++i) {
dfs(nums, goal, i + 1, sum + nums[i]); // Notice that this is i+1...... It's easy to get wrong
}
}
public:
int minAbsDifference(vector<int>& nums, int goal) {
if(nums.empty()){
return goal;
}
dfs(nums, goal, 0, 0);
return ans;
}
};

Summary : Data range n :
- n <= 20, Can be violent ,2^20
- n <= 40, No direct violence , But it can be half ,20 * 2^20
边栏推荐
- Establishment of terminal security capability verification environment and penetration test records
- 模式-“里氏替换原则”
- 示波器探头对信号源阻抗的影响
- Popular science | does poor English affect the NPDP exam?
- Material design component - use bottomsheet to show extended content (II)
- Hdu2377bus pass (build more complex diagram +spfa)
- 基于AVFoundation实现视频录制的两种方式
- 启牛2980有没有用?开户安全吗、
- POJ 3414 pots (bfs+ clues)
- Determine the best implementation of horizontal and vertical screens
猜你喜欢

实现浏览页面时校验用户是否已经完成登录的功能

从架构上详解技术(SLB,Redis,Mysql,Kafka,Clickhouse)的各类热点问题

EN 438-7 laminated sheet products for building covering decoration - CE certification

MySQL deep paging optimization with tens of millions of data, and online failure is rejected!

Write an interface based on flask

Using webassembly to operate excel on the browser side

Pytoch practice -- MNIST dataset handwritten digit recognition

教你自己训练的pytorch模型转caffe(三)

How to make ERP inventory accounts of chemical enterprises more accurate

Interpreting the daily application functions of cooperative robots
随机推荐
The transformation based on vertx web sstore redis to realize the distributed session of vertx HTTP application
@Validated basic parameter verification, grouping parameter verification and nested parameter verification
PHP deserialization +md5 collision
基于vertx-web-sstore-redis的改造实现vertx http应用的分布式session
Clion-MinGW编译后的exe文件添加ico图标
hdu2377Bus Pass(构建更复杂的图+spfa)
产品好不好,谁说了算?Sonar提出分析的性能指标,帮助您轻松判断产品性能及表现
第05章_存储引擎
R language [data management]
@Validated基础参数校验、分组参数验证和嵌套参数验证
poj 3414 Pots (bfs+线索)
Is Kai Niu 2980 useful? Is it safe to open an account
Pytoch practice -- MNIST dataset handwritten digit recognition
Deep merge object deep copy of vant source code parsing
Test of incombustibility of cement adhesives BS 476-4
ts 之 属性的修饰符public、private、protect
Duchefa cytokinin dihydrozeatin (DHZ) instructions
Aitm 2-0003 horizontal combustion test
leetcode:1755. 最接近目标值的子序列和
Simple getting started example of Web Service