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;            }}


原创粉丝点击