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

Combinations ——LeetCode

时间:2015-05-29 11:32:26      阅读:79      评论:0      收藏:0      [点我收藏+]

标签:

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,输出所有长度为k的排列组合。

解题思路:当做求子集来做,大于k的剪枝剪掉,最后再筛一下结果集。

    public List<List<Integer>> combine(int n, int k) {

        List<List<Integer>> res = new ArrayList<>();
        if(n==0){
            return res;
        }
        res.add(new ArrayList<Integer>());
        helper(res,k,n);
        Iterator<List<Integer>> itr = res.iterator();
        while(itr.hasNext()){
            if(itr.next().size()!=k){
                itr.remove();
            }
        }
        return res;
    }

    private void helper(List<List<Integer>> res,int k,int n){

        for(int j=1;j<=n;j++){
            int currSize = res.size();
            for(int i=0;i<currSize;i++){
                List<Integer> x = new ArrayList<>(res.get(i));
                x.add(j);
                if(x.size()>k)
                    continue;
                res.add(new ArrayList<>(x));
            }
        }
    }

 

Combinations ——LeetCode

标签:

原文地址:http://www.cnblogs.com/aboutblank/p/4537881.html

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