LeetCode-77-Combinations(回溯法)-Medium

 题意理解:

列举从1-n中取出k个数的全部情况(如,[1, 2, 3]中取2个数的结果为[1, 2] [1, 3] [2, 3]);


题目分析:

使用回溯法(深度遍历+剪枝);


解题代码:

public class Solution {
    private ArrayList> ans= new ArrayList>();
    
    private void process(ArrayList list, int[] nums, int initPos, int n){
        if(n==0){
            ans.add(list);
            return;
        }
        
        if(initPos==nums.length){
            return;
        }
        
        for(int i=initPos; i tList= new ArrayList(list);
            tList.add(new Integer(nums[i]));
            process(tList, nums, i+1, n-1);
        }
    }
    
    public List> combine(int n, int k) {
        int[] nums= new int[n];
        for(int i=1; i<=n; i++){
            nums[i-1]=i;
        }
        
        ArrayList list=new ArrayList();
        process(list, nums, 0, k);
        
        return (List)ans;
    }
}


你可能感兴趣的:(LeetCode)