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

leetcode------Combinations

时间:2015-03-16 16:20:45      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

标题:

Combinations

通过率: 30.5%
难度: 中等

 

 

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],
]

到了递归。。我发现我的弱点就是递归。

本题相当于遍历二叉树。应为是正序,不重复,则能做开头的元素就是n-k+1,所以从1开始然后进入迭代,放够k个元素后进行add

具体看代码:

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

 

leetcode------Combinations

标签:

原文地址:http://www.cnblogs.com/pkuYang/p/4341920.html

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