//贪心算法(又称贪婪算法)是指,在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,算法得到的是在某种意义上的局部最优解
//1建立数学模型来描述问题
//2把求解的问题分成若干个子问题
//3对每个子问题求解,得到子问题的局部最优解
//4把子问题的解局部最优解合成原来解问题的一个解
//A、不能保证解是最佳的。因为贪心算法总是从局部出发,并没从整体考虑
//B、贪心算法一般用来解决求最大或最小解
//c、贪心算法只能确定某些问题的可行性范围
//O(n2)
private A: Set<number> = new Set<number>();
private B: Set<number> = new Set<number>();
private C: Set<number> = new Set<number>();
private D: Set<number> = new Set<number>();
//需要包含的内容。
private all: Set<number> = new Set<number>();
//被检查的数据。
private check: Array<any> = new Array<any>();
this.all.add(1); this.all.add(2); this.all.add(3); this.all.add(4);
this.all.add(5); this.all.add(6); this.all.add(7); this.all.add(8);
this.A.add(1); this.A.add(2); this.A.add(3); this.A.add(4);
this.B.add(4); this.B.add(5); this.B.add(6); this.B.add(7); this.B.add(8);
this.C.add(8); this.C.add(7); this.C.add(1); this.C.add(2);
this.D.add(3); this.D.add(4); this.D.add(5); this.D.add(6);
this.check.push(this.A); this.check.push(this.B); this.check.push(this.C); this.check.push(this.D);
this.Greedy(this.all);
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
this.printSet(this.all, "打印结果:");
private Greedy(allTemp: Set<number>) {
//最终输出的组合
let all: Set<number> = new Set<number>();
allTemp.forEach((item, index) => { //根据自己的需求决定是否使用浅拷贝
all.add(item);
});
let finalSet: Set<any> = new Set<any>();
while (all.size > 0) {
let useSet: Set<number> = new Set<number>(); //这次遍历所用到的 集合
let useItem: Set<number> = new Set<number>(); //这次遍历所用到的 item
this.check.forEach((iem, ind) => {
let jiaoji = this.setIntersect(iem, all); //计算交集 。 es6 使用 let jiaoji =new Set([...B].filter(x=>C.has(x)));
if (jiaoji.size > useItem.size) { //找出交集最多 集合
useSet = iem
useItem = jiaoji
}
});
//删除那些本次找到的。
useItem.forEach((item, index) => {
all.delete(item);
});
finalSet.add(useSet);
}
finalSet.forEach((iem, ind) => {
// item是集合
console.log("~~~~~~~~~~~~~```")
this.printSet(iem, "打印结果:");
});
}
private setIntersect(A: Set<any>, B: Set<any>): Set<any> {
if (A == null || B == null) {
return null;
}
const temp: Set<any> = new Set<any>(); //const 的本质: const 定义的变量并非常量,并非不可变,它定义了一个常量引用一个值。使用 const 定义的对象或者数组,其实是可变的。
if (A.size > B.size) { //A的数量比较多
B.forEach((item, index) => {
if (A.has(item)) {
temp.add(item);
}
});
} else { //B的数量比较多
A.forEach((item, index) => {
if (B.has(item)) {
temp.add(item);
}
});
}
return temp;
}
private printSet(s: Set<Number>, tips: string) {
s.forEach((item, index) => { //遍历 效率不高,因为每一个都遍历。
console.log(tips, index, ":", item);
});
}