简单算法的实现——集合
集合论中算法——并、交、差、笛卡尔积
1 import java.io.*; 2 import java.util.*; 3 public class Union { 4 public static void main(String[] args) throws IOException{ 5 int i=0,j=0,k=0; 6 Set<Integer> A =new HashSet<Integer>(); 7 Set<Integer> B =new HashSet<Integer>(); 8 Set<Integer> C =new HashSet<Integer>(); 9 10 System.out.println("请输入集合A、B的元素个数:"); 11 Scanner s=new Scanner(System.in); 12 int m=s.nextInt(); 13 int n=s.nextInt(); 14 System.out.println("请输入集合A元素:"); 15 for(;i<m;i++){ 16 int a=s.nextInt(); 17 A.add(a); 18 } 19 System.out.println("请输入集合B元素:"); 20 for(;j<n;j++){ 21 int b=s.nextInt(); 22 B.add(b); 23 } 24 System.out.println("集合A中的元素:"+A.toString()); 25 System.out.println("集合B中的元素:"+B.toString()); 26 System.out.print("请输入数字选择集合A、B的运算(1 并集 2 交集 3差集 4 笛卡尔积):" ); 27 28 int x=s.nextInt(); 29 if(x==1){ 30 //并集 31 C.clear(); 32 C.addAll(A); 33 C.addAll(B); 34 System.out.println("并集结果:"+C.toString()); 35 36 } 37 else if(x == 2){ 38 //交集 39 C.clear(); 40 C.addAll(A); 41 C.retainAll(B); 42 System.out.println("交集结果:"+C.toString()); 43 } 44 else if(x == 3){ 45 //差集 46 C.clear(); 47 C.addAll(A); 48 C.removeAll(B); 49 System.out.println("差集结果:"+C.toString()); 50 51 } 52 else if(x==4){ 53 List<String> list1 = new ArrayList<String>(); 54 list1.add("a"); 55 list1.add("b"); 56 List<String> list2 = new ArrayList<String>(); 57 list2.add("0"); 58 list2.add("1"); 59 list2.add("2"); 60 List<List<String>> dimValue = new ArrayList<List<String>>(); 61 dimValue.add(list1); 62 dimValue.add(list2); 63 64 // 递归实现笛卡尔积 65 Solution sol = new Solution(); 66 List<List<String>> res = sol.descartes(dimValue); 67 System.out.println("递归实现笛卡尔乘积: 共 " + res.size() + " 个结果"); 68 for (List<String> list : res) { 69 for (String string : list) { 70 System.out.print(string + " "); 71 } 72 System.out.println(); 73 } 74 75 76 } 77 else return; 78 } 79 } 80 class Solution{ 81 public List<List<String>> descartes(List<List<String>> dimValue) { 82 List<List<String>> res = new ArrayList<>(); 83 if (dimValue == null || dimValue.size() == 0) 84 return res; 85 backtrace(dimValue, 0, res, new ArrayList<>()); 86 return res; 87 88 } 89 //递归求解 90 //param dimValue 原始数据集合 91 //param index 当前执行的集合索引 92 //param result 结果集合 93 //param curList 当前的单个结果集 94 private void backtrace(List<List<String>> dimValue, int index, 95 List<List<String>> result, List<String> curList) { 96 if (curList.size() == dimValue.size()) 97 result.add(new ArrayList<>(curList)); 98 else 99 for (int j = 0; j < dimValue.get(index).size(); j++) { 100 curList.add(dimValue.get(index).get(j)); 101 backtrace(dimValue, index + 1, result, curList); 102 curList.remove(curList.size() - 1); 103 } 104 105 } 106 }