您的位置:首页 > 其它

【LeetCode】Combinations

2014-05-11 17:10 369 查看
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 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;

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: