leetcode 368. Largest Divisible Subset 类似LISS最长递增子序列问题 + DP动态规划

来源:互联网 发布:高考改革 知乎 编辑:程序博客网 时间:2024/06/06 05:32

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]

仔细想一下,这道题可以转化为和LISS最长递增子序列一样的问题去使用DP动态规划求解,这道题很值得反思。

代码如下:

import java.util.ArrayList;import java.util.Arrays;import java.util.List;/* * 和LISS最长递增子序列做法思路完全一样 *  * 1.先将数字排序; * 2.dp[i]表示nums[i]可以整除的最多数; * 3.有递推公式 dp[i]=max(dp[i],dp[j]+1) if dp[i]%dp[j]==0, j<i; * */class Solution {    public List<Integer> largestDivisibleSubset(int[] nums)     {        List<Integer> res=new ArrayList<>();        if(nums==null || nums.length<=0)            return res;        if(nums.length==1)        {            res.add(nums[0]);            return res;        }        int[] dp=new int[nums.length];        Arrays.fill(dp, 1);        int [] pre=new int[nums.length];        for(int i=0;i<nums.length;i++)            pre[i]=i;        int maxLen=0,maxIndex=0;        Arrays.sort(nums);        for(int i=0;i<nums.length;i++)        {            for(int j=0;j<i;j++)            {                if(nums[i]%nums[j]==0 && dp[j]+1>dp[i])                {                    dp[i]=dp[j]+1;                    pre[i]=j;                }               }            if(dp[i]>maxLen)            {                maxLen=dp[i];                maxIndex=i;            }        }        int i=maxIndex;        while(pre[i]!=i)        {            res.add(nums[i]);            i=pre[i];        }        res.add(nums[i]);        return res;    }}
阅读全文
0 0
原创粉丝点击