leetcode_1187. Make Array Strictly Increasing 使数组严格递增_[DP]

2021-02-11 18:19

阅读:460

标签:als   upper   ssi   int   element   cond   替换   col   索引   

给你两个整数数组 arr1 和 arr2,返回使 arr1 严格递增所需要的最小「操作」数(可能为 0)。

每一步「操作」中,你可以分别从 arr1 和 arr2 中各选出一个索引,分别为 i 和 j,0

如果无法让 arr1 严格递增,请返回 -1。

 

示例 1:

输入:arr1 = [1,5,3,6,7], arr2 = [1,3,2,4]
输出:1
解释:用 2 来替换 5,之后 arr1 = [1, 2, 3, 6, 7]。
示例 2:

输入:arr1 = [1,5,3,6,7], arr2 = [4,3,1]
输出:2
解释:用 3 来替换 5,然后用 4 来替换 3,得到 arr1 = [1, 3, 4, 6, 7]。
示例 3:

输入:arr1 = [1,5,3,6,7], arr2 = [1,6,3,3]
输出:-1
解释:无法使 arr1 严格递增。
 

提示:

1
0


题解

 

Intuition

For any operation, we need to pick the smallest possible element from the second array. So, we can start by sorting the second array.

Solution

Run the search with two branches:

 

  • Keep the current element (if increasing),
  • add an operation.

 

Return the minimum of these branches. For memoisation, use indexes of the first and second arrays.

基于上述思路,状态应表示为[i1, i2, prev],但是由于i2与prev有直接关系,因此状态可以简化为[i1, i2],关于这点,题解作者是这样解释的: i2 is in the direct correlation with prev. We could also memoise on [i1][prev] but prev can be quite large (so we would use a hash map).

class Solution {
public:
    int makeArrayIncreasing(vectorint>& arr1, vectorint>& arr2) {
        int len1 = arr1.size(), len2 = arr2.size();
        sort(arr2.begin(), arr2.end());
        vectorint>> dp(len1+1, vectorint>(len2+1, -1));
        int result = dfs(0, 0, INT_MIN, arr1, arr2, dp);
        return result 2001 ? result : -1;
    }

    int dfs(int idx1, int idx2, int prev, vectorint> &arr1, vectorint> &arr2, vectorint>> &dp){
        if(idx1 >= arr1.size())
            return 0;
        if(dp[idx1][idx2] >= 0)
            return dp[idx1][idx2];
        int result = 2001;
        if(arr1[idx1] > prev)
            result = min(result, dfs(idx1+1, idx2, arr1[idx1], arr1, arr2, dp));
        idx2 = upper_bound(arr2.begin()+idx2, arr2.end(), prev) - arr2.begin();
        if(idx2  arr2.size())
            result = min(result, dfs(idx1+1, idx2+1, arr2[idx2], arr1, arr2, dp)+1);
        return dp[idx1][idx2] = result;
    }
};

 

 

leetcode_1187. Make Array Strictly Increasing 使数组严格递增_[DP]

标签:als   upper   ssi   int   element   cond   替换   col   索引   

原文地址:https://www.cnblogs.com/jasonlixuetao/p/12735083.html


评论


亲,登录后才可以留言!