首页 > 其他 > 详细

【LeetCode】Combinations

时间:2014-05-14 03:54:07      阅读:420      评论: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],
]
bubuko.com,布布扣
public class Solution {
    public ArrayList<ArrayList<Integer>> combine(int n, int k) {
        if(k>n)
            return null;
        ArrayList<Integer> ai = new ArrayList<Integer>();
        ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();
        for(int m=0;m<n;m++){
            ai=new ArrayList<Integer>();
            ai.add(m+1);
            re.add(ai);
        }
        for(int i=1;i<k;i++){
            Iterator<ArrayList<Integer>> it = re.iterator();
            ArrayList<ArrayList<Integer>> tempre = new ArrayList<ArrayList<Integer>>();
            while(it.hasNext()){
                ArrayList<Integer> temp = it.next();
                int tt = temp.get(temp.size()-1);
                for(int j=tt+1;j<=n;j++){
                    ArrayList<Integer> newtemp = new ArrayList<Integer>();
                    newtemp.addAll(temp);
                    
                    newtemp.add(j);
                    tempre.add(newtemp);
                }
            }
            re=tempre;
        }
        return re;
        
    }
}
bubuko.com,布布扣

 

【LeetCode】Combinations,布布扣,bubuko.com

【LeetCode】Combinations

原文:http://www.cnblogs.com/yixianyixian/p/3721944.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!