回溯法 已知两个非负整数n和k(n>=k),列出集合S={a1,a2,~,an}的所有k组合

/**
 * 已知两个非负整数n和k(n>=k),列出集合S={a1,a2,~,an}的所有k组合
 * @author JH
 *
 */
public class four {
    private static int k;
    private static int count =0;

    public static void init(int[] list) {
        List tmp = new ArrayList<>();
        Arrays.sort(list);
        zuhe(0, tmp, list);
    }

    private static void zuhe(int curIdx, List tmp, int[] list) {
        if (curIdx <= list.length&&tmp.size()==k) {
            System.out.println(tmp);
            count++;
        }
        for (int i = curIdx; i < list.length; i++) {
            if (i > curIdx && list[i] == list[i - 1])
                continue;
            tmp.add(list[i]);
            zuhe(i + 1, tmp, list);
            tmp.remove(tmp.size() - 1);
        }
    }

    @SuppressWarnings("resource")
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("输入非负整数N");
        int n = s.nextInt();
        int list[] = new int[n];
        System.out.print("输入集合内所有数字");
        for (int i = 0; i < n; i++) {
            list[i] = s.nextInt();
        }
        System.out.print("输入子集整数个数");
        k = s.nextInt();

        init(list);
        System.out.println(count+"种组合");
    }
}

你可能感兴趣的:(算法)