码迷,mamicode.com
首页 > 其他好文 > 详细

77. Combinations

时间:2017-05-30 00:35:32      阅读:259      评论:0      收藏:0      [点我收藏+]

标签:mat   logs   targe   return   array   java   discus   pos   title   

题目:

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

77. Combinations

标签:mat   logs   targe   return   array   java   discus   pos   title   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!