Forráskód Böngészése

新增排列组合类

gaoxing 8 éve
szülő
commit
559315b47f

+ 71 - 0
cqb-comm-utils/src/main/java/com/qmth/cqb/utils/CombinationUtils.java

@@ -0,0 +1,71 @@
+package com.qmth.cqb.utils;
+
+import java.util.ArrayList;
+import java.util.List;
+
+public class CombinationUtils {
+
+    private static List<String> combineList = new ArrayList<String>();
+
+    public static List<Integer> combiantion(List<Integer> numbers, int needNum, int needNestNum) {
+        List<Integer> returnList = new ArrayList<Integer>();
+        if (numbers == null || numbers.size() == 0) {
+            return null;
+        }
+        List<Integer> list = new ArrayList<Integer>();
+        for (int i = 1; i <= numbers.size(); i++) {
+            combine(numbers, 0, i, list);
+        }
+        for (String str : combineList) {
+            returnList = sum(str, needNum, needNestNum);
+            if (returnList.size() > 0) {
+                break;
+            }
+        }
+        return returnList;
+    }
+
+    // 从字符数组中第begin个字符开始挑选number个字符加入list中
+    private static void combine(List<Integer> cs, int begin, int number, List<Integer> list) {
+        if (number == 0) {
+            combineList.add(list.toString());
+            return;
+        }
+        if (begin == cs.size()) {
+            return;
+        }
+        list.add(cs.get(begin));
+        combine(cs, begin + 1, number - 1, list);
+        list.remove(cs.get(begin));
+        combine(cs, begin + 1, number, list);
+    }
+
+    public static void main(String args[]) {
+        // List<Integer> list = new ArrayList<Integer>();
+        // list.add(3);
+        // list.add(4);
+        // list.add(5);
+        // combiantion(list);
+        // System.out.println(combineList.toString());
+    }
+
+    private static List<Integer> sum(String str, int needNum, int needNestNum) {
+        List<Integer> list = new ArrayList<Integer>();
+        List<Integer> tempList = new ArrayList<Integer>();
+        String[] strs = str.replaceAll("\\[", "").replaceAll("\\]", "").split(",");
+        Integer sum = 0;
+        if (strs.length == needNestNum) {
+            for (String intStr : strs) {
+                intStr = intStr.trim();
+                sum += Integer.valueOf(intStr);
+                tempList.add(Integer.valueOf(intStr));
+
+            }
+            if (sum <= needNum) {
+                list.addAll(tempList);
+            }
+        }
+
+        return list;
+    }
+}