77. 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],
]
Hide Tags
 Backtracking 

链接:  http://leetcode.com/problems/combinations/

5/29/2017

25ms, 75%

 1 public class Solution {
 2     public List<List<Integer>> combine(int n, int k) {
 3         List<List<Integer>> ret = new ArrayList<>();
 4         if (n < k) return ret;
 5         
 6         ArrayList<Integer> list = new ArrayList<Integer>();
 7         combination(n, k, ret, list, 1);
 8         return ret;
 9     }
10     
11     private void combination(int n, int k, List<List<Integer>> ret, ArrayList<Integer> list, int pos) {
12         if (list.size() == k) {
13             ret.add(new ArrayList<Integer>(list));
14             return;
15         }
16         for (int i = pos; i <= n; i++) {
17             list.add(i);
18             combination(n, k, ret, list, i + 1);
19             list.remove(list.size() - 1);
20         }
21     }
22 }

别人的答案

这个不理解

https://discuss.leetcode.com/topic/12537/a-short-recursive-java-solution-based-on-c-n-k-c-n-1-k-1-c-n-1-k

iterative方法,还没有理解

https://discuss.leetcode.com/topic/8543/iterative-java-solution

Python神人

https://discuss.leetcode.com/topic/14626/1-liner-3-liner-4-liner

更多讨论

https://discuss.leetcode.com/category/85/combinations

原文地址:https://www.cnblogs.com/panini/p/6919397.html