[leetcode] 368. Largest Divisible Subset

    对于一个排好序的数列nums, nums[i] % nums[j] = 0 且 nums[j] % nums[k] = 0 则有 nums[i] % nums[k] = 0. 
    因此可以用动态规划:  
    用maxpos记录该子列的结尾元素下标;
    数组num用num[i]记录以nums[i]为结尾元素的满足条件的子列的最大元素个数;
    数组index用index[i]记录可以整除nums[i]的最大元素nums[j]的下标j; 
    则有,若nums[i] % nums[j] = 0, 则 num[i] = num[j] + 1 以及 index[i] = j.
    代码如下:
class Solution {
public:
    vector<int> largestDivisibleSubset(vector<int>& nums) {
        if (nums.size() == 0 || nums.size() == 1) {
            return nums;
        }
        sort(nums.begin(), nums.end());
        int max = 1, maxpos = 0;
        int *num = new int[nums.size()];
        int *index = new int[nums.size()];
        num[0] = 1; index[0] = -1;
        for (int i = 1; i < nums.size(); i++) {
            num[i] = 1; index[i] = -1;
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0) {
                    num[i] = num[j] + 1;
                    index[i] = j;
                    if (max < num[i]) {
                        max = num[i];
                        maxpos = i;
                    }
                }
            }
        }
        vector<int> ans;
        int i = maxpos;
        while (i != -1) {
            ans.push_back(nums[i]);
            i = index[i];
        }
        return ans;
    }
};
点赞