Effacer les filtres
Effacer les filtres

Need help with an error

1 vue (au cours des 30 derniers jours)
Ryan W
Ryan W le 15 Oct 2022
Commenté : Jeffrey Clark le 19 Oct 2022
function [nums] = lengthOfLIS(array)
n = length(array);
lis=[];
lis(1)=1;
for i=1:n
lis(i) = 1;
for j=1:i
if(array(i) > array(j) && lis(i) < lis(j)+1)
lis(i) = lis(j)+1;
end
end
end
nums = max(lis);
end

Réponses (1)

Jeffrey Clark
Jeffrey Clark le 18 Oct 2022
@Ryan W, try this instead - you need to look at all possible sequential value sets so a recusive function seems applicable. This could be done as a different named second function (first part of if) called by lengthOfLIS (else part of if):
function [nums] = lengthOfLIS(array,varargin)
if nargin-1 % this is a recursive call so look at all values greater than the last
nums = 0;
for i = find(array>varargin{1})
nums = max(nums,1+lengthOfLIS(array(i+1:end),array(i)));
end
else % this is the first call so look at all initial candidates
nums = 1;
for i = find(array(1:end-1)<array(2:end))
nums = max(nums,1+lengthOfLIS(array(i+1:end),array(i)));
end
end
end
  1 commentaire
Jeffrey Clark
Jeffrey Clark le 19 Oct 2022
@Ryan W if you want to see how it gets its count this version will show the numerically increasing indexes and corresponding numerically increasing array values before returning the length. Results of a run:
testLen = lengthOfLIS(randi(100,1,100))
5 7 19 24 25 41 42 53 54 58 59 66 85 87 96 99 100
21 24 26 27 32 41 45 53 54 68 75 76 77 81 84 87 99
testLen =
17
function [nums] = lengthOfLIS(array,varargin)
if nargin-1
nums = [];
for i = find(array>varargin{1})
nextnums = i+lengthOfLIS(array(i+1:end),array(i));
if length(nextnums)>=length(nums)
nums = [i nextnums];
end
end
else
nums = 1;
for i = find(array(1:end-1)<array(2:end))
nextnums = i+lengthOfLIS(array(i+1:end),array(i));
if length(nextnums)>=length(nums)
nums = [i nextnums];
end
end
disp([nums;array(nums)])
nums = length(nums);
end
end

Connectez-vous pour commenter.

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by