Combinations --- LeetCode

来源:互联网 发布:淘宝高仿鞋店铺 2016 编辑:程序博客网 时间:2024/05/22 17:51

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

解题思路:组合问题,使用递归

public class Solution {
    
   public List<List<Integer>> combine(int n, int k) {
          List<List<Integer>> result=new ArrayList<List<Integer>>();
          if(n<k||k<=0||n<=0){
        return null;  
          }
          Stack<Integer> stack=new Stack<Integer>();                     
          count(1,n,k,result,stack);                  
          return result;
    }
    
    @SuppressWarnings("unchecked")
public void count(int start,int n,int k,List<List<Integer>> result,Stack<Integer> stack){
    if(k==0){
       result.add((List<Integer>)stack.clone()); 
    }   
    for(int i=start;i<=n;i++){
     stack.push(i);
     if(k>0){
    count(i+1,n,k-1,result,stack);  
     }
     stack.pop();     
    }      
    }
    
}




0 0
原创粉丝点击