# Need help with an error

1 回表示 (過去 30 日間)
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 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 件のコメント-1 件の古いコメントを表示-1 件の古いコメントを非表示
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 Center および File ExchangeLogical についてさらに検索

### Community Treasure Hunt

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

Start Hunting!

Translated by