标签:leetcode
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; }
LeetCode——Combinations,布布扣,bubuko.com
标签:leetcode
原文地址:http://blog.csdn.net/laozhaokun/article/details/37810615