组合
题目
组给出两个整数n和k,返回从1……n中选出的k个数的组合。
样例
例如 n = 4 且 k = 2
返回的解为:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]题解
典型的回溯法题型。
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<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
find(n,result,new ArrayList<Integer>(),k,1);
return result;
}
private void find(int n,List<List<Integer>> result,ArrayList<Integer> list,int k,int value)
{
if (list.size() == k)
{
result.add(list);
return;
}
for (int i=value;i<=n;i++)
{
ArrayList<Integer> ls = new ArrayList<Integer>(list);
ls.add(i);
find(n,result,ls,k,i+1);
}
}
}
Last Update 2016.10.17