[Leetcode]368. Largest Divisible Subset
2016-07-18 15:45
295 查看
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj)
of elements in this subset satisfies: Si % Sj =
0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
Example 2:
of elements in this subset satisfies: Si % Sj =
0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
nums: [1,2,3] Result: [1,2] (of course, [1,3] will also be ok)
Example 2:
nums: [1,2,4,8] Result: [1,2,4,8]
class Solution { public: vector<int> largestDivisibleSubset(vector<int>& nums) { if (nums.empty()) { return {}; } sort(nums.begin(), nums.end()); vector<int> dp(nums.size() , 1); vector<int> prev(nums.size(), -1); int maxIdx = 0; for (int i = 0; i < nums.size(); ++i) { for (int j = 0; j < i; ++j) { if (nums[i] % nums[j] == 0) { if (dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; prev[i] = j; } } } if (dp[maxIdx] < dp[i]) { maxIdx = i; } } vector<int> result; for (int i = maxIdx; i != -1; i = prev[i]) { result.push_back(nums[i]); } return result; } };
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解