日期:2014-05-20 浏览次数:20709 次
import java.util.Scanner; /** * 输出1的被选中。0的未被选中 * @author * */ public class Choose { public static void showTeams(int[] array, int i, int chooseNum) { if (i >= array.length) { int cnt = 0; for (int j = 0; j < array.length; ++j) cnt += array[j]; if (cnt == chooseNum) { for (int j = 0; j < array.length; ++j) System.out.print(array[j] + " "); System.out.println(); } return; } array[i] = 1; ++i; showTeams(array, i, chooseNum); array[i - 1] = 0; showTeams(array, i, chooseNum); } public static void main(String[] args) { int total, chooseNum; Scanner sc = new Scanner(System.in); total = sc.nextInt(); chooseNum = sc.nextInt(); int[] array = new int[total]; for (int i = 0; i < array.length; ++i) array[i] = 0; showTeams(array, 0, chooseNum); } }
------解决方案--------------------
这个是输出编号 mark[]里面放编号 import java.util.Scanner; public class Choose { public static void showTeams(int[] array, int i, int chooseNum, int[] mark) { if (i >= array.length) { int cnt = 0; for (int j = 0; j < array.length; ++j) cnt += array[j]; if (cnt == chooseNum) { for (int j = 0; j < array.length; ++j) { if (array[j] == 1) System.out.print(mark[j] + " "); } System.out.println(); } return; } array[i] = 1; ++i; showTeams(array, i, chooseNum, mark); array[i - 1] = 0; showTeams(array, i, chooseNum, mark); } public static void main(String[] args) { int total, chooseNum; Scanner sc = new Scanner(System.in); total = sc.nextInt(); chooseNum = sc.nextInt(); int[] array = new int[total]; int[] mark = new int[total]; for (int i = 0; i < array.length; ++i) { array[i] = 0; mark[i] = i + 1; } showTeams(array, 0, chooseNum, mark); } }
------解决方案--------------------
我也来凑个热闹,
贴个用泛型的
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class ChooseMInN2 { static int total; static int need; static List<Integer> selected = new ArrayList<Integer>(); public static void showTeams(int current ) { if (selected.size()==need){ //成功 System.out.println(selected); return; } if (current>total) return; //失败 showTeams(current+1); //不加当前元素,继续探索 selected.add(current); showTeams(current+1); //加当前元素,继续探索 selected.remove(new Integer(current)); //回溯 } public static void main(String[] args) { Scanner sc = new Scanner(System.in); total = sc.nextInt(); need = sc.nextInt(); showTeams(1); } }
------解决方案--------------------
又是排列组合的问题,凑个热闹吧,递归和非递归写法