LeetCode Largest Divisible Subset(动态规划)

来源:互联网 发布:企业淘宝账户怎么注册 编辑:程序博客网 时间:2024/06/08 17:46

题意:给出一个数组,找出子集合,使得每对可以除尽

思路:将数组从小到大排序,用动态规划方法

代码如下:

public class Solution{    public int[] largestDivisibleSubset(int[] nums)    {        if (null == nums || 0 == nums.length) return nums;        Arrays.sort(nums);        int[] count = new int[nums.length];        int[] p = new int[nums.length];        int maxCnt = 0;        int startIndex = 0;        for (int i = nums.length - 1; i >= 0; i--)        {            for (int j = i; j < nums.length; j++)            {                if (nums[j] % nums[i] == 0 && count[i] < 1 + count[j])                {                    count[i] = 1 + count[j];                    p[i] = j;                    if (count[i] > maxCnt)                    {                        maxCnt = count[i];                        startIndex = i;                    }                }            }        }       int[] res = new int[maxCnt];        int cnt = 0;        while (startIndex != p[startIndex])        {            res[cnt++] = nums[startIndex];            startIndex = p[startIndex];        }        res[cnt++] = nums[startIndex];        return res;    }}


0 0
原创粉丝点击