8.13 dp: triangle & maximumSubArr & palindromePartitionII

to do

8.13 dp: triangle & maximumSubArr & palindromePartitionII_第1张图片

13.1] Triangle

一开始理解错了,adjacent是说下一行可以保持index或是index+1

- naive method

n*n space and build from top of triangle to bottom

    int minimumTotal(vector>& triangle) {
        if (triangle.empty()) return 0;
        int lastLineLen = triangle[triangle.size()-1].size();

        vector> minSum (triangle.size(), vector(lastLineLen, INT_MAX) );
        minSum[0][0] = triangle[0][0];
        for (int row=1; row=triangle[row-1].size()) continue;
                    minSum[row][index] = min(minSum[row][index], minSum[row-1][lastRowIndex]+triangle[row][index]);
                }
                // cout<<"minSum["<

- Better version.

Use O(n) space and build from bottom to top in avoidance of index out of bound

    int minimumTotal(vector>& triangle) {
        if (triangle.empty()) return 0;
        vector lowerRow = triangle[triangle.size()-1];
        for (int row=triangle.size()-2; row>=0; --row) {
            vector higherRow(triangle[row].size(), -1);
            for (int i=0; i

13.2] maximum-subarray

- If exists no negative numbers, simply keep adding to find the maximum.

    int maxSubArray(vector& nums) {
        int maxSoFar = 0, maxEndingHere = 0; 
        for (int i=0; i

- add the negative cases. It means we'll make comprimise when considering if we should add the last new number.

  • Assume we've solved subproblems where input string length <=n and stored answers in array maxSumArr: maxSumArr[i] gives the maximum sum of subarrary ending with s[i].
  • Now consider incremental step where string s of length n+1
    • case 1: add s[n+1] to maxSumArr[n]. Only meaningful if maxSumArry[n]>=0
    • case 2: Else if maxSumArry[n]<0, start newSubArray with s[n+1]
    • => maxSumArry[n+1] = max(maxSumArry[n]+s[n+1], s[n+1]);
    • base case: maxSumArry[0] = s[0]
    • what to return?
    int maxSubArray(vector& nums) {
        vector maxSumArr = {nums[0]};
        for (int i=1; i

mark redo w/ divide and conquer

优化的暴破法只要O(n)是的只要O(n)你没有看错走过路过不要错过

13.3] Palindrome Partitioning II

redo !!!!

dp for isPalin table,
dp for partitioning string

    bool isPalindrome(string s) {
        for (int l=0, r=s.size()-1; l> isPalin(s.size(), vector(s.size(), true));
        // build isPalin lookup table
        for (int i=s.size()-1; i>=0; --i) {
            for (int j=i; j minCut(s.size(), INT_MAX);
        for (int i=0; i

你可能感兴趣的:(8.13 dp: triangle & maximumSubArr & palindromePartitionII)