题意理解:
列举从1-n中取出k个数的全部情况(如,[1, 2, 3]中取2个数的结果为[1, 2] [1, 3] [2, 3]);
题目分析:
使用回溯法(深度遍历+剪枝);
解题代码:
public class Solution {
private ArrayList<ArrayList<Integer>> ans= new ArrayList<ArrayList<Integer>>();
private void process(ArrayList<Integer> list, int[] nums, int initPos, int n){
if(n==0){
ans.add(list);
return;
}
if(initPos==nums.length){
return;
}
for(int i=initPos; i<nums.length; i++){
ArrayList<Integer> tList= new ArrayList(list);
tList.add(new Integer(nums[i]));
process(tList, nums, i+1, n-1);
}
}
public List<List<Integer>> combine(int n, int k) {
int[] nums= new int[n];
for(int i=1; i<=n; i++){
nums[i-1]=i;
}
ArrayList<Integer> list=new ArrayList<Integer>();
process(list, nums, 0, k);
return (List)ans;
}
}