LintCode:最长上升子序列

LintCode:最长上升子序列

LIS转化为LCS问题,动态规划。

Python

class Solution:
    """ @param nums: The integer array @return: The length of LIS (longest increasing subsequence) """
    def longestIncreasingSubsequence(self, nums):
        # write your code here
        n = len(nums)
        ans = [[0 for i in range(n+1)] for i in range(n+1)]
        s_nums = sorted(nums)

        for i in range(1, n+1):
            for j in range(1, n+1):
                if s_nums[i-1] == nums[j-1]:
                    ans[i][j] = ans[i][j-1] + 1
                else:
                    ans[i][j] = max(ans[i-1][j], ans[i][j-1])

        return ans[n][n]

Java

public class Solution {
    /** * @param nums: The integer array * @return: The length of LIS (longest increasing subsequence) */
    public int longestIncreasingSubsequence(int[] nums) {
        // write your code here
        if(nums.length == 0){
            return 0;
        } 
        int[] s_nums = nums.clone();
        Arrays.sort(s_nums);
        int m = nums.length;
        int[][] ans = new int[m+1][m+1];

        for(int i=0; i<m+1; i++){
            for(int j=0; j<m+1; j++){
                if(i==0 || j==0){
                    ans[i][j] = 0;
                }
                else{
                    if(s_nums[i-1] == nums[j-1]){
                        ans[i][j] = ans[i][j-1] + 1;
                    }
                    else{
                        ans[i][j] = Math.max(ans[i][j-1], ans[i-1][j]);
                    }
                }

            }
        }
        return ans[m][m];
    }
}

你可能感兴趣的:(动态规划)