package cn.com.qmth.examcloud.core.questions.base;

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;
    }
}