LeetCode.368 Largest Divisible Subset(经典DP问题)
来源:互联网 发布:联通网络电话卡 编辑:程序博客网 时间:2024/06/05 00:56
题目:
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
nums: [1,2,3]Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8]Result: [1,2,4,8]分析(经典DP问题):
class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { //求最长子串,满足任意一对%为0 //思路:经典的DP问题 List<Integer> list=new ArrayList<>(); if(nums.length==0||nums==null) return list; //对数组进行排序 Arrays.sort(nums); int [] dp=new int[nums.length]; Arrays.fill(dp,1); //求最长长度的集合 int max=1; for(int i=1;i<nums.length;i++){ for(int j=i-1;j>=0;j--){ if(nums[i]%nums[j]==0){ dp[i]=Math.max(dp[i],dp[j]+1); //记录最长的子集 max=Math.max(max,dp[i]); } } } int last = 0; //从后往前查找,直到找到max,那么前面便包含属于其的子集 for (int i = nums.length - 1; i >= 0 && max >= 0; i--) { if (dp[i] == max && last % nums[i] == 0) { last = nums[i]; //从末尾插入 list.add(0, nums[i]); max--; } } return list; }}
阅读全文
0 0
- LeetCode.368 Largest Divisible Subset(经典DP问题)
- Leetcode 368 - Largest Divisible Subset(dp)
- LeetCode 368 Largest Divisible Subset
- LeetCode 368: Largest Divisible Subset
- LeetCode[368] Largest Divisible Subset
- leetcode(368):Largest Divisible Subset
- LeetCode #368: Largest Divisible Subset
- [LeetCode.368]Largest Divisible Subset
- Leetcode 368 Largest Divisible Subset
- 【Leetcode】Largest Divisible Subset
- 【Leetcode】Largest Divisible Subset
- <LeetCode>Largest Divisible Subset
- Leetcode Largest Divisible Subset
- [LeetCode] Largest Divisible Subset
- [leetcode-368]Largest Divisible Subset(java)
- 【LEETCODE】368- Largest Divisible Subset [Python]
- leetcode:数学:Largest Divisible Subset(368)
- LeetCode Largest Divisible Subset(动态规划)
- 初识设计模式
- 习题7.2
- android省电和提高效率
- CodeForces-a
- 数位和
- LeetCode.368 Largest Divisible Subset(经典DP问题)
- 跨链技术之ILP详解及应用
- 【Scikit-Learn 中文文档】模型评估: 量化预测的质量
- Spring boot 集成JavaMail服务发送邮件
- Json的知识点
- JAVA集合
- Dota2 AI 简易开发教程
- 20171127 自省
- 程序员专用的简历神器,让你制作简历更简单,方便,专业