LeetCode——Combinations

简介:

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,如需转载请自行联系原作者

相关文章
[LeetCode]--17. Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:D
1298 0
LeetCode - 17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个数字串,输出其在手机九宫格键盘上的所有可能组合.
921 0
[LeetCode] Combinations
A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts: What is a partial solution and when is it fi...
810 0
[LeetCode] Letter Combinations of a Phone Number
Well, a typical backtracking problem. Make sure you are clear with the following three problems: What is a partial solution and when is it finished?...
896 0

热门文章

最新文章