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],
]
[code]
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> list=new ArrayList<List<Integer>>();
if(n<k || k==0)return list;
List<List<Integer>> l1=combine(n-1, k), l2=combine(n-1, k-1);
for(List<Integer> entry:l1)list.add(new ArrayList<Integer>(entry));
if(k==1)
{
ArrayList<Integer> temp=new ArrayList<Integer>();
temp.add(n);
list.add(temp);
}
else
{
for(List<Integer> entry:l2)
{
ArrayList<Integer> temp=new ArrayList<Integer>(entry);
temp.add(n);
list.add(temp);
}
}
return list;
}
}
[Thoughts]
ending conditions要仔细考虑