Leetcode递增三元子序列:记忆化递归优化未全过用例求指导
关于递增三元子序列问题的优化疑问
我正在Leetcode上求解递增三元子序列问题。最初采用暴力递归解法,虽通过多数测试用例但出现超时问题,代码如下:
public static void main(String[] args) { IncreasingTriplet it = new IncreasingTriplet(); int[] nums = { 1, 5, 0, 4, 1, 3 }; System.out.println(it.increasingTriplet(nums)); } public boolean increasingTriplet(int[] nums) { // if there are less than 3 numbers return false; if (nums.length < 3) return false; return helper(nums, nums.length, Integer.MIN_VALUE, 0, 0); } private boolean helper(int[] nums, int n, int prev, int index, int count) { if (index >= n) { if (count < 3) { return false; } else if (count == 3) { return true; } return false; } else if (count == 3) { return true; } else if (count > 3) { return false; } if (nums[index] > prev) { if (helper(nums, n, nums[index], index + 1, count + 1) || helper(nums, n, prev, index + 1, count)) { return true; } return false; } return helper(nums, n, prev, index + 1, count); }
之后我尝试通过构建二维缓存cache[index][count],记录每个索引作为递增三元序列第1、2、3位的状态来优化,但仍无法通过全部测试用例。请问该思路是否存在问题?恳请提供指导建议。优化后的代码如下:
public boolean increasingTriplet(int[] nums) { //if there are less than 3 numbers return false; if(nums.length < 3) return false; int[][]cache = new int[nums.length][4]; for(int i = 0; i < cache.length; i++){ for(int j = 0; j < cache[0].length; j++){ cache[i][j] = -1; } } return helper(nums, nums.length, Integer.MIN_VALUE, 0, 0, cache); } //Let's optimize by keeping track of the index as either part of the sequence as 1st, 2nd or 3rd and then store that for future use. private boolean helper(int[] nums, int n, int prev, int index, int count, int[][]cache){ if(index >= n){ if(count < 3){ return false; } if( count == 3){ return true; } return false; } if(count == 3){ return true; } if(count > 3){ return false; } if(cache[index][count] != -1){ return cache[index][count] == 1? true:false; } if(nums[index] > prev){ if(helper(nums, n, nums[index], index + 1, count + 1, cache) || helper(nums, n, prev, index + 1, count, cache)){ cache[index][count] = 1; return true; } cache[index][count] = 0; return false; } return helper(nums, n, prev, index + 1, count, cache); }
内容的提问来源于stack exchange,提问作者Spindoctor
相关产品推荐
相关产品推荐

