编程题:输入两个参数,N和M,用M个数字加起来等于N.

 

我理解成了从M个数中,找出和为N的组合。

 

public class SubSet {

    public static void main(String[] args) {
        int[] m = { 1, 2, 3, 4 };
        int n = 3;

//        getBinarySubSet(5);
        getGroupSumEqualN(m, n);
    }

    public static void getGroupSumEqualN(int[] m, int n) {
        // get list which contains integer < n;
        List<Integer> newM = new ArrayList<Integer>();
        for(int i : m) {
            if(i <= n)
                newM.add(i);
        }
        
        System.out.println(newM);

        // take subset
        int sum;
        int len = newM.size();

        for(int subSet = 0, backSubSet = 0; subSet < (0x1 << len); subSet = backSubSet + 1) {
            sum = 0;
            backSubSet = subSet;
            for(int i =0; i<len; i++) {
                if((subSet & 0x01) == 1) {
                    sum += newM.get(i);
                }
                subSet = subSet >> 1;
            }
            if(sum == n) {
                System.out.println(Integer.toBinaryString(backSubSet));
            }
        }
    }

    static List<Integer> getBinarySubSet(int n) {
        // sample : n = 3, get "000, 001, 010, 011, 100, 101, 110, 111".
        List<Integer> list = new ArrayList<Integer>();
        if(n < 1)
            return list;
        int i = 0x00;
        while(i < (0x01 << n)) {
            System.out.println(Integer.toBinaryString(i));
            list.add(i);
            i++;
        }
        return list;
    }
}

 

 

输入时:

[1, 2, 3]
11
100

 

 

就是1+2,和3的组合。其中用的关键了全枚举所有组合。