368.largest-divisible-subset.go 596 B

12345678910111213141516171819202122232425262728293031
  1. func largestDivisibleSubset(nums []int) (res []int) {
  2. n := len(nums)
  3. if n <= 1 {
  4. return nums
  5. }
  6. sort.Sort(sort.Reverse(sort.IntSlice(nums)))
  7. dp, adj := make([]int, n), make([]int, n)
  8. for i := 0; i < n; i++ {
  9. dp[i], adj[i] = 1, -1
  10. }
  11. max, idx := 0, 0
  12. for i := 1; i < n; i++ { // DP + math
  13. for j := 0; j < i; j++ {
  14. if nums[j]%nums[i] != 0 {
  15. continue
  16. }
  17. if dp[i] < dp[j]+1 {
  18. dp[i], adj[i] = dp[j]+1, j
  19. }
  20. if max < dp[i] {
  21. max, idx = dp[i], i
  22. }
  23. }
  24. }
  25. for adj[idx] != -1 {
  26. res = append(res, nums[idx])
  27. idx = adj[idx]
  28. }
  29. return append(res, nums[idx])
  30. }