- 贪婪算法(贪心算法)是指在对问题进行求解时,在每一步选择中都采取最好或者最优(即最有利的选择, 从而希望能够导致结果是最好或者最优的算法
- 贪婪算法所得到的结果不一定是最优的结果(有时候会是最优解),但是都是相对近似(接近)最优解的结果
集合覆盖问题
function getMinLeitai (boardcasts) {
const allAreas = new Set();
[...boardcasts.keys()].forEach(key => {
boardcasts.get(key).forEach(item => allAreas.add(item))
});
const selects = []
let tempArr = []
let maxKey = null
while (allAreas.size > 0) {
maxKey = null
for (item of boardcasts) {
tempArr = item[1].filter(val => allAreas.has(val))
if (tempArr.length && (maxKey === null || boardcasts.get(maxKey).length < tempArr.length)) {
maxKey = item[0]
}
}
if (maxKey !== null) {
selects.push(maxKey)
boardcasts.get(maxKey).forEach(val => allAreas.delete(val))
}
}
return selects
}
var map = new Map()
map.set('k1', ['北京', '上海', '天津'])
map.set('k2', ['广州', '北京', '深圳'])
map.set('k3', ['成都', '上海', '杭州'])
map.set('k4', ['上海', '天津'])
map.set('k5', ['杭州', '大连'])
console.log(getMinLeitai(map).join(', '))
最少硬币找零
function minCoinChange(coins, amount) {
const change = [];
let total = 0;
coins.sort((a, b) => b - a); // 贪心算法体现
for (let i = 0; i < coins.length; i++) {
const coin = coins[i];
while (total + coin <= amount) {
change.push(coin);
total += coin;
}
}
return change;
}
console.log(minCoinChange([1, 2, 10, 5], 26).join(', '))