标签:div html nts [] 并且 desc pair i++ target
原题链接在这里:https://leetcode.com/problems/largest-divisible-subset/description/
题目:
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:
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]
题解:
类似Longest Increasing Subsequence.
DP 问题. 求最长的subset, subset中每两个数大的除以小的余数是0. 储存到当前点, 包括当前点, 符合要求的最大subset长度.
递推时, 当前点 i 前面每一个点 j 若可以被 i 整除 并且 1+j 点对应的最长subset长度 比现有 i 点对应的最长subset长度长, 就更新 i 点对应的最长subset长度. 同时更新 i 的整除对应关系.
初始化, 最长subset就是当前点. 长度为1.
答案 维护最长subset对应的index, 并通过记录的整除对应关系找回所有点.
Time Complexity: O(n^2). n = nums.length.
Space: O(n).
AC Java:
1 class Solution { 2 public List<Integer> largestDivisibleSubset(int[] nums) { 3 List<Integer> res = new ArrayList<Integer>(); 4 if(nums == null || nums.length == 0){ 5 return res; 6 } 7 8 Arrays.sort(nums); 9 10 int len = nums.length; 11 int [] count = new int[len]; 12 int [] pre = new int[len]; 13 int max = 0; 14 int index = -1; 15 16 for(int i = 0; i<len; i++){ 17 count[i] = 1; 18 pre[i] = -1; 19 20 for(int j = 0; j<i; j++){ 21 if(nums[i]%nums[j] == 0 && count[i]<count[j]+1){ 22 count[i] = count[j]+1; 23 pre[i] = j; 24 } 25 } 26 27 if(count[i] > max){ 28 max = count[i]; 29 index = i; 30 } 31 } 32 33 while(index != -1){ 34 res.add(nums[index]); 35 index = pre[index]; 36 } 37 38 return res; 39 } 40 }
LeetCode Largest Divisible Subset
标签:div html nts [] 并且 desc pair i++ target
原文地址:http://www.cnblogs.com/Dylan-Java-NYC/p/7619919.html