Need help with an error

1 次查看(过去 30 天)
Ryan W
Ryan W 2022-10-15
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

回答(1 个)

Jeffrey Clark
Jeffrey Clark 2022-10-18
@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 个评论
Jeffrey Clark
Jeffrey Clark 2022-10-19
@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

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Graphics Object Programming 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by