leetecode 673
看到标签是动态规划就自己想了个状态方程
dp[i][k] += dp[j][k-1] if(nums[i]>nums[j],0<=j<i)
class Solution {
public int findNumberOfLIS(int[] nums) {
int[][] dp =new int[nums.length+1][nums.length+1];
for(int i=0;i<nums.length;i++){
dp[i][1] = 1;
}
int res = 0;
int maxK = 1;
for(int i=0;i<nums.length;i++){
for(int k=1;k<=i+1;k++){
if(dp[i][k] != 0) maxK = Math.max(maxK,k);
for(int j=0;j<i;j++){
if(nums[i] > nums[j] && j>=k-2){
dp[i][k] += dp[j][k-1];
if(dp[i][k] != 0) maxK = Math.max(maxK,k);
}
}
}
}
for(int i=maxK-1;i<nums.length;i++){
res += dp[i][maxK];
}
return res;
}
}
这是我写的代码,运行后发现超时。
看了下官方解答的动态规划,发现是用两个一维数组实现了我上述的想法,这难道就是空间换时间??
class Solution {
public int findNumberOfLIS(int[] nums) {
//原本我的状态方程是dp[i][k] += dp[j][k-1] if(nums[i]>nums[j])
int N = nums.length;
if (N <= 1) return N;
int[] lengths = new int[N]; //lengths[i] = length of longest ending in nums[i]
int[] counts = new int[N]; //count[i] = number of longest ending in nums[i]
Arrays.fill(counts, 1);
for (int j = 0; j < N; ++j) {
for (int i = 0; i < j; ++i) if (nums[i] < nums[j]) {
if (lengths[i] >= lengths[j]) {
lengths[j] = lengths[i] + 1;
counts[j] = counts[i];
} else if (lengths[i] + 1 == lengths[j]) {
counts[j] += counts[i];
}
}
System.out.println(lengths[j]);
}
int longest = 0, ans = 0;
for (int length: lengths) {
longest = Math.max(longest, length);
}
for (int i = 0; i < N; ++i) {
if (lengths[i] == longest) {
ans += counts[i];
}
}
return ans;
}
}
学到了。