加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

【Leetcode】Largest Divisible Subset

发布时间:2020-12-13 21:11:45 所属栏目:PHP教程 来源:网络整理
导读:题目链接: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 th

题目链接: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,4,8]

Result: [1,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的前1位数的下标 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; }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读