从M个里取N个的组合 C(m,n)

用递归写的,使用时要注意栈空间问题


	/**
	 * 从m个里取n个的所有组合 c(m,n)
	 * 
	 * @param m
	 * @param n
	 * @return
	 */
	public static List<List<Integer>> getCombinationList(int m, int n) {
		if (n == 1) {
			List<List<Integer>> resultList = new ArrayList<List<Integer>>();
			for (int i = 1; i <= m; i++) {
				resultList.add(new ArrayList<Integer>(Arrays.asList(i)));
			}

			return resultList;
		}

		List<List<Integer>> nMinusOneCombList = getCombinationList(m, n - 1);
		List<List<Integer>> resultList = new ArrayList<List<Integer>>();
		for (List<Integer> nMinusOneComb : nMinusOneCombList) {
			for (int number = 1; number <= m; number++) {
				List<Integer> comb = new ArrayList<Integer>();
				comb.addAll(nMinusOneComb);
				Integer maxOfNminusOneComb = nMinusOneComb.get(nMinusOneComb.size() - 1);
				if (number <= maxOfNminusOneComb) {
					continue;
				}
				comb.add(number);
				resultList.add(comb);
			}

		}

		return resultList;

	}



	public static void main(String[] args) {
		List<List<Integer>> resultList = getCombinationList(4, 2);
		for (List<Integer> list : resultList) {
			System.out.println(list);

		}
	}
   

执行main后输出:

[1, 2]

[1, 3]

[1, 4]

[2, 3]

[2, 4]

[3, 4]

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.