且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

LeetCode——Combinations

更新时间:2022-09-18 08:47:50

Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
原题链接:https://oj.leetcode.com/problems/combinations/

题目:给定两个整数n和k,返回全部的k个1……n中的数的组合。

思路:递归。

	public List<List<Integer>> combine(int n, int k) {
		return combine(1, n + 1, k);
	}

	public List<List<Integer>> combine(int low, int upper, int k) {
		List<List<Integer>> result = new ArrayList<List<Integer>>();
		if (k == 1) {
			for (int i = low; i < upper; i++) {
				List<Integer> r = new ArrayList<Integer>();
				r.add(i);
				result.add(r);
			}
			return result;
		}
		for (int i = low; i < upper; i++) {
			List<List<Integer>> r = combine(i + 1, upper, k - 1);
			for (List<Integer> a : r) {
				a.add(0, i);
			}
			result.addAll(r);
		}
		return result;
	}

reference : http://www.laurashawn.net/?p=10907






本文转自mfrbuaa博客园博客,原文链接:http://www.cnblogs.com/mfrbuaa/p/5183816.html,如需转载请自行联系原作者