解题思路:
- 用动态规划得到dp[i] represents the largest divisible subset numbers.
代码:
class Solution {
public List<Integer> largestDivisibleSubset(int[] nums) {
List<Integer> res = new ArrayList<>();
if(nums == null || nums.length == 0) return res;
int len = nums.length;
int[] dp = new int[len];
Arrays.fill(dp, 1);
Arrays.sort(nums);
for(int i = 1; i < len; i++){
for(int j = i - 1; j >= 0; j--){
if(nums[i] % nums[j] == 0){
dp[i] = Math.max(dp[i], dp[j] + 1);
}
}
}
int maxIndex = 0;
for(int i = 1; i < len; i++){
maxIndex = dp[i] > dp[maxIndex] ? i : maxIndex;
}
int temp = nums[maxIndex];
int curDp = dp[maxIndex];
for(int i = maxIndex; i >= 0; i--){
if(temp % nums[i] == 0 && dp[i] == curDp){
res.add(nums[i]);
temp = nums[i];
curDp--;
}
}
return res;
}
}
网友评论