1947. 最大兼容性评分和

88 阅读1分钟

题目:
leetcode.cn/problems/ma…
算法:
方法一:回溯

func maxCompatibilitySum(students [][]int, mentors [][]int) int {
    ans := 0
    n := len(students[0])
    allocatedMentors := make([]int, len(mentors))
    var dfs func(stu int) int 
    // 给这个学生分配一个mentor,返回兼容性
    dfs =  func(stu int) int {
        if stu >= len(students) {
            return 0
        }
        maxCompatibility := 0
        for i := range mentors {
            // 对所有未分配的mentor,计算兼容性
            if allocatedMentors[i] == 1 {
                continue
            }
            cur := 0
            allocatedMentors[i] = 1
            for j := 0; j < n; j ++ {
                if students[stu][j] == mentors[i][j] {
                    cur ++
                }
            }
            // 总的兼容性 =  当前兼容性 +  后续兼容性
            maxCompatibility = max(maxCompatibility, cur + dfs(stu + 1))
            allocatedMentors[i] = 0
        }
        return maxCompatibility
    }
    for i := range students {
        ans = max(ans, dfs(i))
    }
    return ans
}

func max(a, b int) int {
    if a > b {
        return a 
    }
    return b
}