如何解决记忆最长升序子序列递归
我正在解决最长(严格)升序子序列问题,我必须在给定整数数组的情况下返回子序列的长度。我想出了这个递归:
int maxLength = 0;
int longestAscendingSubsequenceLength(int[] nums) {
longestAscendingSubsequenceLength(nums,null,-1,null);
return maxLength;
}
void longestAscendingSubsequenceLength(int[] nums,int lengthSoFar,Set<Integer> indexesToExclude,int bottomNumIndex,Integer bottomNum) {
for (int i=bottomNumIndex + 1; i < nums.length; i++) {
if (indexesToExclude!= null && indexesToExclude.contains(i)) {
continue;
}
int newBottomNum = nums[i];
if (indexesToExclude != null) {
indexesToExclude.add(i);
}
if ( (bottomNum == null) || (bottomNum < newBottomNum) ){
maxLength = Math.max(maxLength,lengthSoFar + 1);
longestAscendingSubsequenceLength(nums,lengthSoFar + 1,indexesToExclude,i,newBottomNum);
}
}
}
这有效,但几乎是一种蛮力方法,对于长时间的输入,它需要永远。我很难记住这个,因为每个调用都有多个改变的参数,所以如果我要使用 HashMap 作为备忘录,我不确定使用什么作为“键”,这样我就可以避免冗余计算。任何人都可以帮助或指出我正确的方向吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。