LeetCode 368. Largest Divisible Subset

原題連接在這裏:https://leetcode.com/problems/largest-divisible-subset/description/html

題目:post

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.this

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

Example 1:spa

nums: [1,2,3]

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

Example 2:code

nums: [1,2,4,8]

Result: [1,2,4,8]

題解:htm

 求最長的subset, subset中每兩個數大的除以小的餘數是0. 儲存到當前點, 包括當前點, 符合要求的最大subset長度.blog

Let count[i] denotes largest subset ending with i.ip

For all j < i, if nums[i] % nums[j] == 0, then i could be added after j and may construct a largeer subset. Update count[i]. element

But how to get the routine. Use preIndex[i] denotes the pre index of i in the largest subset. Then could start with last index and get pre num one by one. 

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         
 5         if(nums == null || nums.length == 0){
 6             return res;    
 7         }
 8         
 9         int len = nums.length;
10         Arrays.sort(nums);
11         int [] count = new int[len];
12         int [] preIndex = new int[len];
13         int resCount = 0;
14         int resIndex = -1;
15         
16         for(int i = 0; i<len; i++){
17             count[i] = 1;
18             preIndex[i] = -1;
19             for(int j = 0; j<i; j++){
20                if(nums[i]%nums[j] == 0 && count[j]+1 > count[i]){
21                    count[i] = count[j]+1;
22                    preIndex[i] = j;
23                } 
24             }
25             
26             if(resCount < count[i]){
27                 resCount = count[i];
28                 resIndex = i;
29             }
30         }
31         
32         while(resIndex != -1){
33             res.add(0, nums[resIndex]);
34             resIndex = preIndex[resIndex];
35         }
36         
37         return res;
38     }
39 }

相似Longest Increasing Subsequence

相關文章
相關標籤/搜索