[leetcode][dp]801. 使序列递增的最小交换次数

题目[leetcode][dp]801. 使序列递增的最小交换次数_第1张图片

解法

主要算法:动态规划
https://leetcode-cn.com/problems/minimum-swaps-to-make-sequences-increasing/comments/2636

Code (C++)

class Solution {
public:
    int minSwap(vector<int>& A, vector<int>& B) {
        int dp[2] = {0,1};
        for ( int i = 1 ; i < A.size() ; i++ ){
            if ( A[i] > A[i-1] && B[i] > B[i-1] ){
                if ( B[i] > A[i-1] && A[i] > B[i-1] ){
                    dp[0] = min(dp[1],dp[0]);
                    dp[1] = min(dp[1],dp[0])+1;
                }else{
                    dp[1] += 1;
                }
            }else{
                int te = dp[0];
                dp[0] = dp[1];
                dp[1] = te+1; 
            }
        }
        return min(dp[0],dp[1]);
    }
};

Code (Java)

class Solution {
    public int minSwap(int[] A, int[] B) {
        int [] dp = new int[2];
        dp[0] = 0;
        dp[1] = 1;
        for ( int i = 1 ; i < A.length ; i++ ){
            if ( A[i] > A[i-1] && B[i] > B[i-1] ){
                if ( B[i] > A[i-1] && A[i] > B[i-1] ){
                    dp[0] = Math.min(dp[1],dp[0]);
                    dp[1] = dp[0] + 1;
                }else{
                    dp[1] = dp[1]+1;
                }
            }else{
                int te = dp[0];
                dp[0] = dp[1];
                dp[1] = te+1;
            }
        }
        
        return Math.min(dp[0],dp[1]);
    }
}

你可能感兴趣的:(leetcode)