LintCode : 组合


组合 

组给出两个整数n和k,返回从1......n中选出的k个数的组合。

您在真实的面试中是否遇到过这个题?

Yes

样例

例如 n = 4 且 k = 2

返回的解为:

[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
标签  Expand   

相关题目  Expand 
解题思路:
典型的回溯算法。
public class Solution {
    /**
     * @param n: Given the range of numbers
     * @param k: Given the numbers of combinations
     * @return: All the combinations of k numbers out of 1..n
     */
    public List> combine(int n, int k) {
          // write your code here
          if(n==0||k==0) return null;
         List>  res = new  ArrayList<>();
         ArrayList cur  = new  ArrayList<>();
         getcombineList(n, k, 0, res, cur,1);
         return res;
    }
   public void getcombineList(int n,int k,int x,List> res,ArrayList cur,int start ){
         if(x==k){
              res.add(new ArrayList(cur));
              return;
         }
         for(int i = start;i<=n;i++){
              cur.add(i);
              getcombineList(n, k, x+1, res, cur,i+1);
              cur.remove(cur.size()-1);
              }
         }
   
}

你可能感兴趣的:(LintCode,算法,面试)