leetcode 368. Largest Divisible Subset

result记录当前列表的长度,pre记录达到最长的上一个数字的索引,最后将数值一个一个添加至list1的

首端。返回list1.

class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
      
        if(nums.length==0){
            return new ArrayList<Integer>();
        }
        if(nums.length==1){
            List<Integer> array = new ArrayList<Integer>();
            array.add(nums[0]);
            return array;
        }
        Arrays.sort(nums);
        int len = nums.length;
        int[] result=new int[len];
        int[] pre=new int[len];
        result[0]=1;
        pre[0]=-1;
        int max=1;
        int maxIndex=0;
        for(int i=1;i<nums.length;i++){
            result[i]=1;
            pre[i]=-1;
            for(int j=0;j<i;j++){
                if(nums[i]%nums[j]==0&&result[i] < 1 + result[j]){//第二个判断条件很重要,不然有的例子过不去,例如1 2 4 8 9 72,
                    result[i]=result[j] + 1;
                    pre[i]=j;
                    if(result[i]>max){
                        max=result[i];
                        maxIndex=i;
                    }
                }
                
            }
        }
        List<Integer> array = new LinkedList<Integer>();
        int index = maxIndex;
        while(index!=-1){
            array.add(0,nums[index]);
            index=pre[index];
        }
        return array;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值