回溯——第77题. 组合
回溯的模板和递归是非常相似的:
递归:
- 确定递归函数的返回值和参数
 - 确定递归的终止条件
 - 确定单层递归的逻辑
 
回溯:
- 确定回溯函数的返回值和参数
 - 确定回溯的终止条件,同时在终止时将本次回溯记录的值回传
 - 确定单层回溯的逻辑
 - 无论回溯终止与否,将本次回溯添加的记录值删除
 
在本题中,代码如下:
1 List<List<Integer>> result = new ArrayList<>(); 2 ArrayList<Integer> temp = new ArrayList<>(); 3 4 public void function(int n, int k, int curr) { 5 temp.add(curr); 6 if (temp.size() == k) { 7 //必须添加记录list的深copy,引用copy会导致result中的temp改变 8 result.add((ArrayList<Integer>) temp.clone()); 9 } 10 else { 11 for (int next = curr+1; next <= n; ++next) { 12 function(n, k, next); 13 } 14 } 15 //无论回溯终止与否,都要删除本次回溯的记录值 16 temp.remove(temp.size()-1); 17 }
回溯可以在递归进入下一层时进行剪枝:
如果下一层的所有元素 + 当前List的所有元素 < k个,则不够了,可以不用进递归了:
    public void function(int n, int k, int curr) {
        temp.add(curr);
        //System.out.println(temp.toString());
        if (temp.size() == k) {
            result.add((ArrayList<Integer>) temp.clone());
        } 
        else {
            if (temp.size() + n-curr >= k) {
                for (int next = curr+1; next <= n; ++next) {
                    function(n, k, next);
                }    
            }        
        }
        temp.remove(temp.size()-1);
    }
                    
                
                
            
        
浙公网安备 33010602011771号