当前位置:网站首页>[leetcode每日一题2021/4/23]368. 最大整除子集
[leetcode每日一题2021/4/23]368. 最大整除子集
2022-07-26 10:33:00 【LittleSeedling】
题目来源于leetcode,解法和思路仅代表个人观点。传送门。
难度:中等
时间:-
tag:排序、动态规划
题目
给你一个由 无重复 正整数组成的集合 nums ,请你找出并返回其中最大的整除子集 answer ,子集中每一元素对 (answer[i], answer[j]) 都应当满足:
answer[i] % answer[j] == 0 ,或
answer[j] % answer[i] == 0
如果存在多个有效解子集,返回其中任何一个均可。
示例 1:
输入:nums = [1,2,3]
输出:[1,2]
解释:[1,3] 也会被视为正确答案。
示例 2:
输入:nums = [1,2,4,8]
输出:[1,2,4,8]
提示:
1 <= nums.length <= 1000
1 <= nums[i] <= 2 * 109
nums 中的所有整数 互不相同
思路
动态规划
第一点:a % b == 0
或 b % a == 0
都能够被接受,那么若a > b
a % b
可能为0
,但b % a
一定不为0
那么,我们将数组【排序】之后,只要判断a(较大的数)是否整除b(较小的数)即可。
第二点:
若a % b == 0
&& b % c==0
=> a % c == 0
但是
a % c == 0
&&b % c == 0
,不能得到a % b == 0
也就是说,%
有【单向传递性】
那么其实这题就可以转换成我们之前非常熟悉的题目【最长上升子序列】。
为什么呢?不难发现其实
>
也有【单向传递性】
第三点:
这题不是求【上升子序列的长度】,而是求【上升子序列】。那么我们只需要一个额外的path数组,记录某个元素的上一个比他小的元素的位置(当前元素的上一个元素什么)(或者说,该元素的dp状态是从哪一个位置转移过来的)。
代码
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int>& nums) {
vector<int> ans;
int n = nums.size();
vector<int> dp(n,1);
//上一个的路径
vector<int> path(n,-1);
//排序
sort(nums.begin(),nums.end());
//最大子集的终点指针
int p = 0;
//找出最大子集的值
int maxAns = 0;
/* * 如果a%b == 0 ,b%c == 0 ,那么 a%c == 0 (单向传递性) * 思路类似【最长上升子序列】 */
for(int i=1;i<n;i++){
for(int j=0;j<i;j++){
if(nums[i] % nums[j] == 0){
if(dp[i] <= dp[j]){
dp[i] = dp[j]+1;
path[i] = j;
}
}
if(maxAns < dp[i]){
maxAns = dp[i];
p = i;
}
}
}
while(p != -1){
ans.push_back(nums[p]);
p = path[p];
}
return ans;
}
};
算法复杂度
时间复杂度: O(n²)。排序时间为O(nlogn)。计算dp数组元素复杂度为O(n²)。
空间复杂度: O(n)。dp数组需要O(n),path数组需要O(n)。
边栏推荐
- js,e.pageX、pageY模态框拖动
- 【socket】三次握手是在listen中完成,accept只从完成连接的队列中拿出一个连接
- C语言回调函数
- [gossip] error loading psychopg2 module: no module named psychopg2
- 抓包工具fiddler和wireshark对比
- 详细解析js中的混合方式构造对象(构造加属性,原型加方法)
- Redis Docker实例与数据结构
- Use spiel expressions in custom annotations to dynamically obtain method parameters or execute methods
- Function templates and non template functions with the same name cannot be overloaded (definition of overloads)
- [Halcon vision] image gray change
猜你喜欢
随机推荐
图片随手机水平移动-陀螺仪。360度设置条件
equals与==的区别
13 以对象管理资源
C语言回调函数
INSTALL_ FAILED_ SHARED_ USER_ Incompatible error resolution
cavans实现静态滚动弹幕
Analyze the hybrid construction objects in JS in detail (construction plus attributes, prototype plus methods)
Dynamically determine file types through links
PLC概述
Kaptcha image verification code integration
js,e.pageX、pageY模态框拖动
移动端双指缩放事件(原生),e.originalEvent.touches
Function templates and non template functions with the same name cannot be overloaded (definition of overloads)
[gossip] error loading psychopg2 module: no module named psychopg2
Deduct daily question 838 of a certain day
Cause: could't make a guess for solution
2022pta平时训练题(1~10题字符串处理问题)
议程速递 | 7月27日分论坛议程一览
[C language] named type and anonymous type
[C language] LINQ overview