题目描述:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
中文理解:
给定两个整数n,k,其中n代表数列1-n,k代表k个元素,从1-n中随机选择k个数字,问共有多少种不重复的组合,每个组合中增序。
解题思路:
使用回溯的方法,首先排除异常情况n小于1和k大于n的情况,然后使用回溯的方法递归实现,具体见代码。
代码(java):
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res =new ArrayList();
if(n<1 || n<k)return res;
traceback(res,new ArrayList<Integer>(),n,k);
return res;
}
public void traceback(List<List<Integer>> res,ArrayList<Integer> tempList,int n,int k){
if(tempList.size()==k){
res.add(new ArrayList(tempList));
return;
}
else{
//这里通过i的设置,保持序列是递增的,同时筛选掉1,4和4,1这种等价的组合。
int i=1;
if(tempList.size()>0)i=tempList.get(tempList.size()-1);
for(;i<=n;i++){
if(tempList.contains(i))continue;
tempList.add(i);
traceback(res,tempList,n,k);
tempList.remove(tempList.size()-1);
}
}
}
}