801. Minimum Swaps To Make Sequences Increasing
问题描述:
We have two integer sequences A
and B
of the same non-zero length.
We are allowed to swap elements A[i]
and B[i]
. Note that both elements are in the same index position in their respective sequences.
At the end of some number of swaps, A
and B
are both strictly increasing. (A sequence is strictly increasing if and only if A[0] < A[1] < A[2] < ... < A[A.length - 1]
.)
Given A and B, return the minimum number of swaps to make both sequences strictly increasing. It is guaranteed that the given input always makes it possible.
Example: Input: A = [1,3,5,4], B = [1,2,3,7] Output: 1 Explanation: Swap A[3] and B[3]. Then the sequences are: A = [1, 3, 5, 7] and B = [1, 2, 3, 4] which are both strictly increasing.
Note:
A, B
are arrays with the same length, and that length will be in the range[1, 1000]
.A[i], B[i]
are integer values in the range[0, 2000]
.
解题思路:
参考了https://www.jianshu.com/p/6021550d227b的解释
可以用动态规划来解答。
类似于背包问题。背包问题为取或不取
而这个问题是,换或不换。
swap[i] 表示换第i个最小的次数
nswap[i]表示不换第i个最小的交换次数。
当A[i-1] < A[i] 以及 B[i-1] < B[i]时,此时若前i-1为严格递增,则此时一定为严格递增。
要么i-1和i位置都不换,要么都换。
所以swap[i] = swap[i-1]+1 ; nswap[i] = nswap[i-1];
考虑只换i的情况,此时应满足:A[i-1] < B[i] && B[i-1] < A[i]
此时:swap[i] = min(swap[i], nswap[i-1] + 1); nswap[i] = min(nswap[i], swap[i-1]);
代码:
class Solution { public: int minSwap(vector<int>& A, vector<int>& B) { int N = A.size(); if(N == 0) return 0; int nswap[1000] = {0}; int swap[1000] = {1}; for(int i = 1; i < N; i++){ nswap[i] = swap[i] = N; if(A[i-1] < A[i] && B[i-1] < B[i]){ nswap[i] = nswap[i-1]; swap[i] = swap[i-1]+1; } if(A[i-1] < B[i] && B[i-1] < A[i]){ nswap[i] = min(nswap[i], swap[i-1]); swap[i] = min(swap[i], nswap[i-1]+1); } } return min(swap[N-1], nswap[N-1]); } };