class Solution { public List<Integer> largestDivisibleSubset(int[] nums) { List<Integer> res = new ArrayList<>(); int n = nums.length; if(n == 0) return res; int[] dp = new int[n]; Arrays.fill(dp,1); Arrays.sort(nums); int max = 1, maxIndex = 0; for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { if(nums[i] % nums[j] == 0) { dp[i] = Math.max(dp[i],dp[j] + 1); } } if(dp[i] > max) { max = dp[i]; maxIndex = i; } } for(int i = maxIndex; i >= 0; i--) { if(nums[maxIndex] % nums[i] == 0 && dp[i] == max) { res.add(nums[i]); maxIndex = i; // 注意 当i > j > k nums[i] % nums[j] == 0 时nums[j] % nums[k] == 0 则有nums[i] % nums[k] == 0 max--; } } return res; } }