【Leetcode】Largest Divisible Subset
2016-06-28 10:18
381 查看
题目链接:https://leetcode.com/problems/largest-divisible-subset/
题目:
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
dp数组表示从0~i包括第i个元素最大的divisible subset size
pre数组用来标记 状态转移过程中的方向,用于回溯最大值时的解集。
dp[i]=max{dp[i],dp[j]+1}
算法:
题目:
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
dp数组表示从0~i包括第i个元素最大的divisible subset size
pre数组用来标记 状态转移过程中的方向,用于回溯最大值时的解集。
dp[i]=max{dp[i],dp[j]+1}
算法:
public List<Integer> largestDivisibleSubset(int[] nums) { LinkedList<Integer> res = new LinkedList<Integer>(); if (nums.length == 0) { return res; } Arrays.sort(nums); int dp[] = new int[nums.length]; //记录从0~i包括nums[i]的最大subset的size int pre[] = new int[nums.length];//记录到当前元素最大size的前一位数的下标 int maxIdx = -1, max = -1; for (int i = 0; i < nums.length; i++) { //初始化 dp[i] = 1; pre[i] = -1; } for (int i = 1; i < nums.length; i++) { for (int j = 0; j < i; j++) { if (nums[i] % nums[j] == 0 && dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; pre[i] = j;// } } } for (int i = 0; i < nums.length; i++) {//找到最大的子集size 和它最后元素的下标 if (dp[i] > max) { max = dp[i]; maxIdx = i; } } for (int i = maxIdx; i >= 0;) { //回溯解集 res.addFirst(nums[i]); i = pre[i]; } return res; }
相关文章推荐
- UI组件
- 读者写者问题-写者优先参考答案(vc代码)
- Podfile文件详解
- swift循环学习
- (4)文件类型和扩展名,node和block
- ContentProvider 开发之简单学习
- Jsoup解析HTML实例及文档方法详解
- 论Object.creat
- ContentProvider 开发之简单学习
- ubuntu修改软件源 安装桌面VMwaretools 共享文件夹
- listview的item中的子条目选中(递归选中)
- Android中的onActivityResult和setResult方法的使用
- (3)linux系统的目录结构
- [Eclipse] - 解决"Java was started but returned exit code = 13"问题
- android SharedPeferences List<String>
- (转)常见的HTTP状态码(HTTP Status Code)说明
- MySql常用命令总结
- android数据库:增删改查
- linux查看cpu、内存、版本信息
- ORACLE:执行计划中BITMAP AND导致sql慢