Need help with an error

조회 수: 1 (최근 30일)
Ryan W
Ryan W 2022년 10월 15일
댓글: Jeffrey Clark 2022년 10월 19일
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에서 Logical에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by