LeetCode113:Path Sum II

37 篇文章 0 订阅
26 篇文章 0 订阅


将当前节点加入到临时存储集中,若满足条件则加入到结果集,否则向下搜索左右子树,在搜索完左右子树后还原(回溯法)

1、概念

回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。

回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法,而满足回溯条件的某个状态的点称为“回溯点”。

许多复杂的,规模较大的问题都可以使用回溯法,有“通用解题方法”的美称。
2、基本思想

在包含问题的所有解的解空间树中,按照深度优先搜索的策略,从根结点出发深度探索解空间树。当探索到某一结点时,要先判断该结点是否包含问题的解,如果包含,就从该结点出发继续探索下去,如果该结点不包含问题的解,则逐层向其祖先结点回溯。(其实回溯法就是对隐式图的深度优先搜索算法)。

若用回溯法求问题的所有解时,要回溯到根,且根结点的所有可行的子树都要已被搜索遍才结束。

而若使用回溯法求任一个解时,只要搜索到问题的一个解就可以结束。
3、用回溯法解题的一般步骤:

(1)针对所给问题,确定问题的解空间:

首先应明确定义问题的解空间,问题的解空间应至少包含问题的一个(最优)解。

(2)确定结点的扩展搜索规则

(3)以深度优先方式搜索解空间,并在搜索过程中用剪枝函数避免无效搜索。

public class Solution {
    public List<List<Integer>> ans = new ArrayList<>();
    public void robot(TreeNode root, int sum , List<Integer> tmp){
        if(root==null)  return;
        tmp.add(root.val);
        sum = sum-root.val;
        if(root.left==null && root.right==null){ //叶子为空
            if(sum==0){ //满足条件
                ans.add(new ArrayList<>(tmp));
            }
        }
        else{ //叶子不为空
                if(root.left!=null)
                    robot(root.left,sum,tmp);
                if(root.right!=null)
                    robot(root.right,sum,tmp);
            }
            //回溯
        sum-=root.val;
        tmp.remove(tmp.size()-1);
    }
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        if(root==null) return ans;
        //List<List<Integer>> ans = new ArrayList<>();
        ans.clear();
        List<Integer> tmp = new ArrayList<>();
        robot(root,sum,tmp);
        return ans;

    }
}
public class Solution {
    public List<List<Integer>> ans = new ArrayList<>();
    public List<Integer> tmp = new ArrayList<>();
    public void robot(TreeNode root, int sum,int cur){
        if(root==null)  return;
        tmp.add(root.val);
        cur+=root.val;
        if(root.left==null && root.right==null && sum==cur){ //叶子节点为空 并且满足当前满足条件
            ans.add(new ArrayList<>(tmp));
        }

        robot(root.left,sum,cur);
        robot(root.right,sum,cur);
        //回溯
        cur-=root.val;
        tmp.remove(tmp.size()-1);
    }
    public List<List<Integer>> pathSum(TreeNode root, int sum) {
        robot(root,sum,0);
        return ans;
    }
}

参考:http://www.cnblogs.com/steven_oyj/archive/2010/05/22/1741376.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值