【月度刷题计划同款】常规状压 DP & 启发式搜索

题目描述

这是 LeetCode 上的 1879. 两个数组最小的异或值之和 ,难度为 困难

Tag : 「状压 DP」、「动态规划」、「启发式搜索」

给你两个整数数组 nums1nums2,它们长度都为 n

两个数组的 异或值之和 为 (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) (下标从 0 开始)。

比方说,[1,2,3][3,2,1] 的 异或值之和 等于 (1 XOR 3) + (2 XOR 2) + (3 XOR 1) = 2 + 0 + 2 = 4

请你将 nums2 中的元素重新排列,使得异或值之和最小 。

请你返回重新排列之后的 异或值之和 。

示例 1:

ini 复制代码
输入:nums1 = [1,2], nums2 = [2,3]

输出:2

解释:将 nums2 重新排列得到 [3,2] 。
异或值之和为 (1 XOR 3) + (2 XOR 2) = 2 + 0 = 2 。

示例 2:

scss 复制代码
输入:nums1 = [1,0,3], nums2 = [5,3,4]

输出:8

解释:将 nums2 重新排列得到 [5,4,3] 。
异或值之和为 (1 XOR 5) + (0 XOR 4) + (3 XOR 3) = 4 + 4 + 0 = 8 。

提示:

  • <math xmlns="http://www.w3.org/1998/Math/MathML"> n = n u m s 1. l e n g t h n = nums1.length </math>n=nums1.length
  • <math xmlns="http://www.w3.org/1998/Math/MathML"> n = = n u m s 2. l e n g t h n == nums2.length </math>n==nums2.length
  • <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 < = n < = 14 1 <= n <= 14 </math>1<=n<=14
  • <math xmlns="http://www.w3.org/1998/Math/MathML"> 0 < = n u m s 1 [ i ] , n u m s 2 [ i ] < = 1 0 7 0 <= nums1[i], nums2[i] <= 10^7 </math>0<=nums1[i],nums2[i]<=107

状压 DP

这是一道「状压 DP」模板题。

为了方便,我们令下标从 <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 1 </math>1 开始。

定义 <math xmlns="http://www.w3.org/1998/Math/MathML"> f [ i ] [ s ] f[i][s] </math>f[i][s] 为考虑前 <math xmlns="http://www.w3.org/1998/Math/MathML"> i i </math>i 个元素,且对 nums2 的使用情况为 <math xmlns="http://www.w3.org/1998/Math/MathML"> s s </math>s 时的最小异或值 。其中 <math xmlns="http://www.w3.org/1998/Math/MathML"> s s </math>s 是一个长度为 <math xmlns="http://www.w3.org/1998/Math/MathML"> n n </math>n 的二进制数:若 <math xmlns="http://www.w3.org/1998/Math/MathML"> s s </math>s 中的第 <math xmlns="http://www.w3.org/1998/Math/MathML"> k k </math>k 位为 <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 1 </math>1,说明 nums2[k] 已被使用;若 <math xmlns="http://www.w3.org/1998/Math/MathML"> s s </math>s 中的第 <math xmlns="http://www.w3.org/1998/Math/MathML"> k k </math>k 位为 <math xmlns="http://www.w3.org/1998/Math/MathML"> 0 0 </math>0,说明 nums2[k] 未被使用。

起始时,只有 <math xmlns="http://www.w3.org/1998/Math/MathML"> f [ 0 ] [ 0 ] = 0 f[0][0] = 0 </math>f[0][0]=0,其余均为无穷大 INF。 <math xmlns="http://www.w3.org/1998/Math/MathML"> f [ 0 ] [ 0 ] f[0][0] </math>f[0][0] 含义为在不考虑任何数,对 nums2 没有任何占用情况时,最小异或值为 <math xmlns="http://www.w3.org/1998/Math/MathML"> 0 0 </math>0。最终 <math xmlns="http://www.w3.org/1998/Math/MathML"> f [ n ] [ 2 n − 1 ] f[n][2^n - 1] </math>f[n][2n−1] 即为答案。

不失一般性考虑 <math xmlns="http://www.w3.org/1998/Math/MathML"> f [ i ] [ s ] f[i][s] </math>f[i][s] 该如何转移,可以以 nums1[i] 是与哪个 nums2[j] 进行配对作为切入点:

  • 由于总共考虑了前 <math xmlns="http://www.w3.org/1998/Math/MathML"> i i </math>i 个成员,因此 <math xmlns="http://www.w3.org/1998/Math/MathML"> s s </math>s 中 <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 1 </math>1 的数量必然为 <math xmlns="http://www.w3.org/1998/Math/MathML"> i i </math>i,否则 <math xmlns="http://www.w3.org/1998/Math/MathML"> f [ i ] [ s ] f[i][s] </math>f[i][s] 就不是一个合法状态,跳过转移

  • 枚举 nums1[i] 是与哪一个 nums2[j] 进行配对的,且枚举的 <math xmlns="http://www.w3.org/1998/Math/MathML"> j j </math>j 需满足在 <math xmlns="http://www.w3.org/1998/Math/MathML"> s s </math>s 中的第 <math xmlns="http://www.w3.org/1998/Math/MathML"> j j </math>j 位值为 <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 1 </math>1,若满足则有

<math xmlns="http://www.w3.org/1998/Math/MathML" display="block"> f [ i ] [ s ] = min ⁡ ( f [ i ] [ s ] , f [ i − 1 ] [ p r e v ] + n u m s 1 [ i ] ⊕ n u m s 2 [ j ] ) f[i][s] = \min(f[i][s], f[i - 1][prev] + nums1[i] ⊕ nums2[j]) </math>f[i][s]=min(f[i][s],f[i−1][prev]+nums1[i]⊕nums2[j])

其中 prev 为将 <math xmlns="http://www.w3.org/1998/Math/MathML"> s s </math>s 中的第 <math xmlns="http://www.w3.org/1998/Math/MathML"> j j </math>j 位进行置零后的二进制数,即 prev = s ^ (1 << j),符号 ⊕ 代表异或操作。

Java 代码:

Java 复制代码
class Solution {
    public int minimumXORSum(int[] nums1, int[] nums2) {
        int n = nums1.length, mask = 1 << n, INF = 0x3f3f3f3f;
        int[][] f = new int[n + 10][mask];
        for (int i = 0; i <= n; i++) Arrays.fill(f[i], INF);
        f[0][0] = 0;
        for (int i = 1; i <= n; i++) {
            for (int s = 0; s < mask; s++) {
                if (getCnt(s, n) != i) continue;
                for (int j = 1; j <= n; j++) {
                    if (((s >> (j - 1)) & 1) == 0) continue;
                    f[i][s] = Math.min(f[i][s], f[i - 1][s ^ (1 << (j - 1))] + (nums1[i - 1] ^ nums2[j - 1]));
                }
            }
        }
        return f[n][mask - 1];
    }
    int getCnt(int s, int n) {
        int ans = 0;
        for (int i = 0; i < n; i++) ans += (s >> i) & 1;
        return ans;
    }
}

C++ 代码:

C++ 复制代码
class Solution {
public:
    int minimumXORSum(vector<int>& nums1, vector<int>& nums2) {
        int n = nums1.size(), mask = 1 << n, INF = 0x3f3f3f3f;
        vector<vector<int>> f(n + 10, vector<int>(mask, INF));
        f[0][0] = 0;
        auto getCnt = [&](int s, int n) {
            int ans = 0;
            for (int i = 0; i < n; i++) ans += (s >> i) & 1;
            return ans;
        };
        for (int i = 1; i <= n; i++) {
            for (int s = 0; s < mask; s++) {
                if (getCnt(s, n) != i) continue;
                for (int j = 1; j <= n; j++) {
                    if (((s >> (j - 1)) & 1) == 0) continue;
                    f[i][s] = min(f[i][s], f[i - 1][s ^ (1 << (j - 1))] + (nums1[i - 1] ^ nums2[j - 1]));
                }
            }
        }
        return f[n][mask - 1];
    }
};

Python 代码:

Python 复制代码
class Solution:
    def minimumXORSum(self, nums1: List[int], nums2: List[int]) -> int:
        n, mask, INF = len(nums1), 1 << len(nums1), 0x3f3f3f3f
        f = [[INF] * mask for _ in range(n + 10)]
        f[0][0] = 0
        for i in range(1, n + 1):
            for s in range(mask):
                if sum([1 for i in range(n) if (s >> i) & 1]) != i:
                    continue
                for j in range(1, n + 1):
                    if ((s >> (j - 1)) & 1) == 0:
                        continue
                    f[i][s] = min(f[i][s], f[i - 1][s ^ (1 << (j - 1))] + (nums1[i - 1] ^ nums2[j - 1]))
        return f[n][mask - 1]

TypeScript 代码:

TypeScript 复制代码
function minimumXORSum(nums1: number[], nums2: number[]): number {
    const n = nums1.length, mask = 1 << n, INF = 0x3f3f3f3f;
    const f: number[][] = new Array(n + 10).fill([]).map(() => new Array(mask).fill(INF));
    f[0][0] = 0;
    const getCnt = (s: number, n: number): number => {
        let ans = 0;
        for (let i = 0; i < n; i++) ans += (s >> i) & 1;
        return ans;
    };
    for (let i = 1; i <= n; i++) {
        for (let s = 0; s < mask; s++) {
            if (getCnt(s, n) !== i) continue;
            for (let j = 1; j <= n; j++) {
                if (((s >> (j - 1)) & 1) === 0) continue;
                f[i][s] = Math.min(f[i][s], f[i - 1][s ^ (1 << (j - 1))] + (nums1[i - 1] ^ nums2[j - 1]));
            }
        }
    }
    return f[n][mask - 1];
};
  • 时间复杂度: <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( n 2 × 2 n ) O(n^2 \times 2^n) </math>O(n2×2n)
  • 空间复杂度: <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( n × 2 n ) O(n \times 2^n) </math>O(n×2n)

模拟退火

事实上,这道题还能使用「模拟退火」进行求解。

由于我们可以无限次对 nums2 进行打乱互换,先来思考如何衡量一个 nums2 排列的"好坏"。

一个简单的方式:固定计算 (nums1[0] XOR nums2[0]) + (nums1[1] XOR nums2[1]) + ... + (nums1[n - 1] XOR nums2[n - 1]) 作为衡量当前 nums2 的得分,得分越小,当前的 nums2 排列越好。

迭代开始前先对 nums2 进行一次随机打乱,随后每个回合随机选择 nums2 的两个成员进行互换,并比较互换前后的得分情况,若互换后变好,那么保留该互换操作;若变差,则以一定概率进行重置(重新换回来)。

重复迭代多次,使用一个全局变量 ans 保存下最小异或值之和。

即「模拟退火」的单次迭代基本流程:

  1. 随机选择两个下标,计算「交换下标元素前对应序列的得分」&「交换下标元素后对应序列的得分」
  2. 如果温度下降(交换后的序列更优),进入下一次迭代
  3. 如果温度上升(交换前的序列更优),以「一定的概率」恢复现场(再交换回来)

对于一个能够运用模拟退火求解的问题,最核心的是如何实现 calc 方法(即如何定义一个具体方案的得分),其余均为模板内容。

Java 代码(2023/08/23 可过):

Java 复制代码
class Solution {
    int N = 400;
    double hi = 1e5, lo = 1e-5, fa = 0.90;
    Random random = new Random(20230823);
    void swap(int[] n, int a, int b) {
        int c = n[a];
        n[a] = n[b];
        n[b] = c;
    }
    int calc() {
        int res = 0;
        for (int i = 0; i < n; i++) res += n1[i] ^ n2[i];
        ans = Math.min(ans, res);
        return res;
    }
    void shuffle(int[] nums) {
        for (int i = n; i > 0; i--) swap(nums, random.nextInt(i), i - 1);
    }
    void sa() {
        shuffle(n2);
        for (double t = hi; t > lo; t *= fa) {
            int a = random.nextInt(n), b = random.nextInt(n);
            int prev = calc();
            swap(n2, a, b);
            int cur = calc(); 
            int diff = cur - prev; 
            if (Math.log(diff / t) >= random.nextDouble()) swap(n2, a, b);
        }
    }
    int[] n1, n2;
    int n;
    int ans = Integer.MAX_VALUE;
    public int minimumXORSum(int[] nums1, int[] nums2) {
        n1 = nums1; n2 = nums2;
        n = n1.length;
        while (N-- > 0) sa();
        return ans;
    }
}
  • 时间复杂度:启发式搜索不讨论时空复杂度
  • 空间复杂度:启发式搜索不讨论时空复杂度

最后

这是我们「刷穿 LeetCode」系列文章的第 No.1879 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:github.com/SharingSour...

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。

更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地 🎉🎉

相关推荐
野曙1 分钟前
快速选择算法:优化大数据中的 Top-K 问题
大数据·数据结构·c++·算法·第k小·第k大
LallanaLee3 分钟前
常见面试题
java·开发语言
Codeking__18 分钟前
”一维前缀和“算法原理及模板
数据结构·算法
休息一下接着来18 分钟前
C++ 条件变量与线程通知机制:std::condition_variable
开发语言·c++·算法
爱尚你199328 分钟前
Java 泛型与类型擦除:为什么解析对象时能保留泛型信息?
java
Code哈哈笑31 分钟前
【机器学习】支持向量回归(SVR)从入门到实战:原理、实现与优化指南
人工智能·算法·机器学习·回归·svm
努力学习的小廉42 分钟前
【C++】 —— 笔试刷题day_29
开发语言·c++·算法
小羊在奋斗44 分钟前
【LeetCode 热题 100】搜索插入位置 / 搜索旋转排序数组 / 寻找旋转排序数组中的最小值
算法·leetcode·职场和发展
全栈派森1 小时前
云存储最佳实践
后端·python·程序人生·flask
meisongqing1 小时前
【软件工程】符号执行与约束求解缺陷检测方法
人工智能·算法·软件工程·软件缺陷