回溯算法组合问题的一个指针细节

1、问题引出

class Solution {
    LinkedList<Integer> path = new LinkedList<>();
    List<List<Integer>> result = new ArrayList<>();
    int sum = 0;
    public List<List<Integer>> combinationSum3(int k, int n) {
        backtracking(k,n,1);
        return result;
    }

    //1、确定回溯的返回值和参数
    public void backtracking(int k, int n, int startIndex){
        //2、确定终止条件
        if(sum > n){return;}
        if(path.size() == k){
            if(sum == n){
                //result.add(path);为什么不行?
                result.add(new ArrayList(path));
            }
            
            return;
        }

        //3、单层逻辑
        for(int i = startIndex; i <= 9; i++){
            sum += i;//这是最要理解的地方,单层中结合数的结构还有下面的回溯来理解
            path.add(i);
            //取数,纵向递归,i+1是因为:例如取到2之后,应该从3开始遍历
            backtracking(k,n,i+1);    
            //回溯
            sum -= i;
            path.removeLast();
        }
    }
}

result.add(path);为什么不行?而要使用result.add(new ArrayList(path));?

2、问题分析

path是一个变量,不是因为每次add(path),key相同而value覆盖这个问题,实际上每次path每次经过计算后,其值发生了变化,由于他是变量,下次add(path)的时候,实际上上一次加入res的path也变成和这次一样了。因为res.add(path)加入的不是固定值,而是指向一个地址的变量!

@Test
    public void testAlgorithm(){
        List<List<Integer>> res = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        path.add(1);
        res.add(path);

        path.add(2);
        res.add(path);
        res.forEach(data-> System.out.print(data+","));//[1, 2],[1, 2],
    }

猜你喜欢

转载自blog.csdn.net/YiGeiGiaoGiao/article/details/128740452