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

Leetcode-Combinations

时间:2014-11-16 09:23:31      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   os   sp   for   div   

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],
]
Have you met this question in a real interview?
 
Analysis:
We need consider the boundary and the return condition very carefully!
 
Solution:
 1 public class Solution {
 2     public List<List<Integer>> combine(int n, int k) {
 3         List<List<Integer>> resSet = new ArrayList<List<Integer>>();
 4         if (n==0 || k==0) return resSet;
 5         List<Integer> curList = new ArrayList<Integer>();
 6         combineRecur(resSet,curList,1,k,n,k);
 7         return resSet;     
 8     }
 9    
10     public void combineRecur(List<List<Integer>> resSet, List<Integer> curList, int curIndex, int numLeft, int n, int k){
11         if (numLeft==1){
12             for (int i=curIndex;i<=n;i++){
13                 curList.add(i);
14                 List<Integer> temp = new ArrayList<Integer>();
15                 temp.addAll(curList);
16                 resSet.add(temp);
17                 curList.remove(curList.size()-1);
18             }
19             return;
20         }
21        
22 
23         for (int i=curIndex;i<=n-numLeft+1;i++){
24             curList.add(i);
25             combineRecur(resSet,curList,i+1,numLeft-1,n,k);
26             curList.remove(curList.size()-1);
27         }
28     }
29         
30 }

 

Leetcode-Combinations

标签:style   blog   io   color   ar   os   sp   for   div   

原文地址:http://www.cnblogs.com/lishiblog/p/4101019.html

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