目录
4.n元素幂集
5.插入排序
6.俄式乘法
7.AVL树
8.数学三角形
9.最长上升子序
10.投资分配
11.活动安排——贪心算法
12.一般背包问题——贪心算法
4.n元素幂集
Java代码:
思路:减一法 ——>利用递推式:p(n) = p(n-1) + IPN (IPN为前项和后项的一种关系)
import java.util.ArrayList;
public class PowerSet {
public static void main(String[] args) {
String[] a = { "1", "2","3", "4" };
ArrayList<String> pn = getSet(a); //
System.out.println("Set size is = " + pn.size());
for (int i = 0; i < a.length; i++) {
String string = a[i];
}
System.out.println(pn.toString());
}
public static ArrayList<String> getSet(String[] a) {
ArrayList<String> pn = new ArrayList<String>(); // creat a list to save set
pn.add("");
for (int i = 0; i < a.length; i++) {
pn.addAll(IPN(pn, a[i])); // 递推式:p(n) = p(n-1) + IPN p(0) = {"","1"}; p(1) = p{"","1","2","1,2"}...
// System.out.println("pn.addAll = " + pn.toString());
// System.out.println("--------------------");
}
return pn;
}
public static ArrayList<String> IPN(ArrayList<String> pn, String i) {
ArrayList<String> tmp = new ArrayList<String>();
for (int k = 0; k < pn.size(); k++) {
// System.out.println("pn.get[k] = " + pn.get(k));
tmp.add(pn.get(k) + i); // 临时list存储元素
// System.out.printf("tmp.get(%d) = %s
", k, tmp.get(k));
}
return tmp;
}
}
运行结果:
Set size is = 16
[, 1, 2, 12, 3, 13, 23, 123, 4, 14, 24, 124, 34, 134, 234, 1234]
C代码
思路:递归法——>树的先序遍历
//递归树的叶子节点 int P(char *str, int n,int index){ static char tmp[10]; int case1 = 0, case2 = 0; if(n==-1){ //递归结束条件,输出叶子节点 tmp[index] = '