[Swift]LeetCode368. 最大整除子集 | Largest Divisible Subset

★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-wgmavpaz-eq.html 
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html

Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:git

Si % Sj = 0 or Sj % Si = 0.github

If there are multiple solutions, return any subset is fine.數組

Example 1:微信

Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok) 

Example 2:app

Input: [1,2,4,8]
Output: [1,2,4,8]

給出一個由無重複的正整數組成的集合,找出其中最大的整除子集,子集中任意一對 (Si,Sj) 都要知足:Si % Sj = 0 或 Sj % Si = 0。ide

若是有多個目標子集,返回其中任何一個都可。 this

示例 1:spa

輸入: [1,2,3]
輸出: [1,2] (固然, [1,3] 也正確)

示例 2:code

輸入: [1,2,4,8]
輸出: [1,2,4,8]

476ms
 1 class Solution {
 2     func largestDivisibleSubset(_ nums: [Int]) -> [Int] {
 3         var nums = nums.sorted(by:<)
 4         var res:[Int] = [Int]()
 5         let number:Int = nums.count
 6         var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:2),count:number)
 7         var mx:Int = 0
 8         var mx_idx:Int = 0
 9         for i in 0..<number
10         {
11             for j in stride(from:i,through:0,by:-1)
12             {
13                 if nums[i] % nums[j] == 0 && dp[i][0] < dp[j][0] + 1
14                 {
15                     dp[i][0] = dp[j][0] + 1
16                     dp[i][1] = j
17                     if mx < dp[i][0]
18                     {
19                         mx = dp[i][0]
20                         mx_idx = i
21                     }                    
22                 }
23             }
24         }
25         for i in 0..<mx
26         {
27             res.append(nums[mx_idx])
28             mx_idx = dp[mx_idx][1]            
29         }
30         return res
31     }
32 }
相關文章
相關標籤/搜索