说是动态规划,其实就是遍历数组,(虽然我没做出来QAQ)每遍历一个的时候都要向前遍历一次找到所有的能整除的
class Solution {
public:
vector<int> largestDivisibleSubset(vector<int> &nums) {
if (nums.size() == 0) {
return vector<int>{};
}
sort(nums.begin(),nums.end());
int n = nums.size();
vector<int> dp(n,0);
vector<int> last(n, 0);
int max = 0, idx = 0;
for (int i = 0; i < n; i++) {
dp[i] = 1;
last[i] = -1;//头一回见这么初始化数组的,有意思
for (int j = 0; j < i; j++) {
if (nums[i] % nums[j] == 0 && dp[j] + 1 > dp[i]) {//更新dp数组
dp[i] = dp[j] + 1;
last[i] = j;//记录前一个数的index,起前向指针的作用
}
}
if (max < dp[i]) {
max = dp[i];
idx = i;
}
}
vector<int> list;
do {
list.push_back(nums[idx]);
idx = last[idx];
} while (idx != -1);
return list;
}
};