LeetCode 368. Largest Divisible Subset(动态规划)

368. Largest Divisible Subset

Medium

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:

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:

Input: [1,2,4,8]
Output: [1,2,4,8]

题意

给定数组nums,求数组中最大的子数组,子数组中两两元素可以整除

思路

动态规划
首先将nums排序,dp[i]含有nums[i]且nums[i]为子数组最大元素的子数组元素个数,递推式
dp[i] = max(dp[j] + 1), for all j in [0, i) st. nums[i] % nums[j] == 0
同时为了记录子数组,另外设一个回溯数组pre, pre[i]表示子数组中nums[i]的前一个元素在nums中的索引

代码

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int n = nums.length;
        if (n == 0) {
            return Collections.emptyList();
        }
        Arrays.sort(nums);
        int i = 0, j = 0, ans = 0, index = 0;
        int[] dp = new int[n], pre = new int[n];
        Arrays.fill(dp, 1);
        Arrays.fill(pre, -1);
        for (i=1; i<n; ++i) {
            for (j=i-1; j>=0; --j) {
                if (nums[i] % nums[j] == 0) {
                    if (dp[j] + 1 > dp[i]) {
                        dp[i] = dp[j] + 1;
                        pre[i] = j;
                    }
                }
            }
            if (dp[i] > ans) {
                ans = dp[i];
                index = i;
            }
        }
        ArrayList<Integer> ret = new ArrayList<>();
        while (index != -1) {
            ret.add(nums[index]);
            index = pre[index];
        }
        return ret;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值