当前位置:网站首页>Dynamic subset division problem
Dynamic subset division problem
2022-04-23 13:45:00 【Du Xiaorui】
Today's daily question is still a dynamic planning question .
Title Description
Title address : The largest divisible subset
Dynamic programming
If violence law is considered, how should this problem be done , The easiest way to think of is to enumerate each element as the beginning , Then traverse the other elements . But this method is not reliable , Take an example :
[ 9 , 18 , 54 , 90 , 108 , 180 , 360 , 540 , 720 ] [9,18,54,90,108,180,360,540,720] [9,18,54,90,108,180,360,540,720] Such an array , from 9 If you start, you'll get [ 9 , 18 , 54 , 108 , 540 ] [9,18,54,108,540] [9,18,54,108,540], But there are actually longer results [ 9 , 18 , 90 , 180 , 360 , 720 ] [9,18,90,180,360,720] [9,18,90,180,360,720], The title requires us to return the longest result , This method is obviously not working .
Let's start thinking about how to use dynamic programming to solve this problem . This problem is a sequence DP problem , Each state depends on the relationship with the previous state , in other words , The current element nums[i] Can you connect it to nums[j] Back , Depending on nums[i] % nums[j] Whether the result is 0. Understand this , So let's define the array dp[],dp[i] Indicates the position of the current element in the sequence . Let's give you an example :
nums | 2 | 4 | 7 | 8 | 9 | 12 | 16 | 20 |
---|---|---|---|---|---|---|---|---|
dp | 1 | 2 | 1 | 3 | 1 | 3 | 4 | 3 |
Defined dp after , How to get dp[i] Well . First, we have to arrange the array from small to large , Because to make nums[i] % nums[j] be equal to 0,nums[i] It must be better than nums[j] Great talent . And then in turn i The previous numbers are % operation , If the result is 0, that dp[i] Is equal to dp[j]+1, That is, in position j After the element of . But because there is more than one element ahead , So we need to update dp[i], Choose the biggest dp[i].
obtain dp Array result , That is, after the results in the table above , Let's go through the table backwards and take out the longest string .
class Solution:
def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
n = len(nums)
nums.sort()
dp = [1] * n
maxSize = 1
maxVal = dp[0]
for i in range(1,n):
for j in range(i):
if nums[i] % nums[j] == 0:
dp[i] = max(dp[i], dp[j]+1)
if dp[i] > maxSize:
maxSize = dp[i]
maxVal = nums[i]
res = []
if maxSize==1:return [nums[0]]
k = n-1
while k >= 0:
if dp[k] == maxSize and maxVal % nums[k] == 0:
res.append(nums[k])
maxVal = nums[k]
maxSize = maxSize-1
k = k-1
return res
maxSize The function of is to record the length of the longest sequence , When the result array is finally obtained, each element is added maxSize Just subtract one .maxVal What is recorded is the maximum value of the maximum sequence , Because when you finally get the result, there may be dp Multiple positions of the array are the same number , It needs to be used at this time maxVal Conduct % operation , The result is 0 Is the element of this result sequence .
Last , Because it's traversing backwards , So the final returned results are in reverse order .
版权声明
本文为[Du Xiaorui]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230556585176.html
边栏推荐
- GDB的使用
- Storage scheme of video viewing records of users in station B
- Detailed explanation and usage of with function in SQL
- [indicators] precision, recall
- Dolphin scheduler configuring dataX pit records
- Oracle database recovery data
- Use future and countdownlatch to realize multithreading to execute multiple asynchronous tasks, and return results after all tasks are completed
- 面试官给我挖坑:URI中的 “//” 有什么用?
- TIA博途中基於高速計數器觸發中斷OB40實現定點加工動作的具體方法示例
- TERSUS笔记员工信息516-Mysql查询(2个字段的时间段唯一性判断)
猜你喜欢
Usereducer basic usage
Search ideas and cases of large amount of Oracle redo log
MySQL index [data structure + index creation principle]
AI21 Labs | Standing on the Shoulders of Giant Frozen Language Models(站在巨大的冷冻语言模型的肩膀上)
JUC interview questions about synchronized, ThreadLocal, thread pool and atomic atomic classes
[point cloud series] neural opportunity point cloud (NOPC)
Three characteristics of volatile keyword [data visibility, prohibition of instruction rearrangement and no guarantee of operation atomicity]
为什么从事云原生开发需要学习容器技术
SAP UI5 应用开发教程之七十二 - SAP UI5 页面路由的动画效果设置
[point cloud series] learning representations and generative models for 3D point clouds
随机推荐
Plato farm, a top-level metauniverse game, has made frequent positive moves recently
[point cloud series] deepmapping: unsupervised map estimation from multiple point clouds
Oracle defines self incrementing primary keys through triggers and sequences, and sets a scheduled task to insert a piece of data into the target table every second
[point cloud series] Introduction to scene recognition
[point cloud series] foldingnet: point cloud auto encoder via deep grid deformation
[point cloud series] multi view neural human rendering (NHR)
Oracle generates millisecond timestamps
Logstash数据处理服务的输入插件Input常见类型以及基本使用
[andorid] realize SPI communication between kernel and app through JNI
【重心坐标插值、透视矫正插值】原理以及用法见解
Lenovo Savior y9000x 2020
Part 3: docker installing MySQL container (custom port)
Core concepts of microservice architecture
OSS cloud storage management practice (polite experience)
[Journal Conference Series] IEEE series template download guide
Oracle renames objects
Search ideas and cases of large amount of Oracle redo log
切线空间(tangent space)
Operations related to Oracle partition
Use future and countdownlatch to realize multithreading to execute multiple asynchronous tasks, and return results after all tasks are completed