适合了解该算法的人理解
// 贪婪算法(覆盖问题)
var obj = {
one: ["a", "b", "r", "s", "q"],
two: ["a", "g", "t", "b", "s", "q", "r"],
three: ["a"],
four: ["p", "c", "b", "n"],
five: ["o", "c", "q", "w", "e"],
six: ["g", "h", "j", "k", "d", "a", "b", "r", "s", "q"],
serve: ["g", "h", "j", "k", "d", "a", "b", "r", "s"],
}
// 存放出现过的字母
var arr_letter = []
// 存放未拥有arr_letter元素最多的obj key值
var arr_obj = []
// 找到未拥有arr_letter元素最多的obj key值
function findMaxobj() {
let maxNode = null
let maxLength = 0
for (let key in obj) {
let length = 0
let node = null
if (arr_obj.indexOf(key) == -1) {
obj[key].forEach(element => {
if (arr_letter.indexOf(element) == -1) {
length++
node = key
}
});
if (maxLength < length) {
maxLength = length
maxNode = node
}
}
}
return maxNode
}
// 贪婪算法
function tanlansuanfa() {
let maxNode = findMaxobj()
while (maxNode != null) {
obj[maxNode].forEach(element => {
arr_letter.push(element)
});
arr_obj.push(maxNode)
maxNode = findMaxobj()
}
}
tanlansuanfa()
console.log(arr_obj)