leetcode--Combinations

来源:互联网 发布:手机知乎怎么查看问题 编辑:程序博客网 时间:2024/06/06 00:17

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

[java] view plain copy
  1. public class Solution {  
  2.     public List<List<Integer>> combine(int n, int k) {  
  3.         List<List<Integer>> res = new ArrayList<List<Integer>>();  
  4.         if(n<=0 || n<k)  return res;  
  5.         helper(n, k, 1new ArrayList<Integer>(),res);  
  6.         return res;  
  7.     }  
  8.       
  9.     public void helper(int n,int k,int start,List<Integer> item,List<List<Integer>> res){  
  10.         if(item.size()==k){  
  11.             res.add(new ArrayList<Integer>(item));  
  12.             return;  
  13.         }  
  14.         for(int i=start;i<=n;i++){  
  15.             item.add(i);  
  16.             helper(n, k, i+1, item,res);  
  17.             item.remove(item.size()-1);  
  18.         }  
  19.           
  20.     }  
  21. }  
原文链接http://blog.csdn.net/crazy__chen/article/details/46420345
原创粉丝点击