国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > 【Leetcode】Largest Divisible Subset

【Leetcode】Largest Divisible Subset

来源:程序员人生   发布时间:2016-07-18 07:57:17 阅读次数:2062次

题目链接: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}

算法:

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; }
生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生