BackTracking

BackTracking (DFS)

39. Combination Sum

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [2, 3, 6, 7] and target 7
A solution set is:

[
  [7],
  [2, 2, 3]
]
public class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> member = new ArrayList<Integer>();
        helper(res, member, candidates, target, 0);
        return res;
    }
    public void helper(List<List<Integer>> res, List<Integer> member, int[] candidates, int target, int start){
       if(target < 0)
            return;
       else if(target == 0){
            res.add(new ArrayList<Integer>(member)); //member is address
            return;
        }
        else{
            for(int i = start; i < candidates.length; i++){
                member.add(candidates[i]);
                helper(res, member, candidates, target - candidates[i], i );
                member.remove(member.size() - 1); //make member empty!
            }
        }
    }
}

40. Combination Sum II

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:

  • All numbers (including target) will be positive integers.
  • The solution set must not contain duplicate combinations.

For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]
public class Solution {
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> member = new ArrayList<>();
        Arrays.sort(candidates);
        boolean visit[] = new boolean[candidates.length];
        helper(res, member, visit, candidates, target, 0);
        return res;
    }
    public void helper(List<List<Integer>> res, List<Integer> member ,boolean[] visit, int[] candidates , int target ,int deep){
        if(target < 0)
            return ;
        else if(target == 0){
            res.add(new ArrayList<Integer>(member));
            return;
        }
        else{
            for(int i = deep; i < candidates.length; i++){
                if(!visit[i]){
                    if (i > 0 && candidates[i] == candidates[i-1] && visit[i-1]==false) continue;
                    member.add(candidates[i]);
                    visit[i] = true;
                    helper(res, member, visit, candidates, target - candidates[i], i);
                    visit[i] = false;
                    member.remove(member.size() - 1);
                }

            }
        }
    }
}
时间: 2024-08-06 01:23:39

BackTracking的相关文章

LeetCode39/40/22/77/17/401/78/51/46/47/79 11道 Backtracking

LeetCode 39 1 class Solution { 2 public: 3 void dfs(int dep, int maxDep, vector<int>& cand, int target) 4 { 5 if (target < 0)return; 6 if (dep == maxDep) 7 { 8 if (target == 0)//到达尾部且等于target 9 { 10 vector<int> temp; 11 for (int i = 0;

重新发现梯度下降法--backtracking line search

一直以为梯度下降很简单的,结果最近发现我写的一个梯度下降特别慢,后来终于找到原因:step size的选择很关键,有一种叫backtracking line search的梯度下降法就非常高效,该算法描述见下图: 下面用一个简单的例子来展示,给一个无约束优化问题: minimize y = (x-3)*(x-3) 下面是python代码,比较两种方法 # -*- coding: cp936 -*- #optimization test, y = (x-3)^2 from matplotlib.p

回溯线搜索 Backtracking line search

机器学习中很多数值优化算法都会用到线搜索(line search).线搜索的目的是在搜索方向上找到是目标函数\(f(x)\)最小的点.然而,精确找到最小点比较耗时,由于搜索方向本来就是近似,所以用较小的代价找到最小点的近似就可以了. Backtracking Line Search(BLS)就是这么一种线搜索算法. BLS算法的思想是,在搜索方向上,先设置一个初始步长\({\alpha _0}\),如果步长太大,则缩减步长,知道合适为止. 上面的想法要解决两个问题: 1. 如何判断当前步长是否合

递归和回溯(recursion and backtracking)

1. Concept Backtracking is a refinement of the brute force approach, which systematically searches for a solution to a problem among all available options. It does so by assuming that the solutions are represented by vectors (v1, ..., vm) of values a

22. Generate Parentheses (backTracking)

Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" /** * R

Notes on Training recurrent networks online without backtracking

Notes on Training recurrent networks online without backtracking Link: http://arxiv.org/abs/1507.07680 Summary   This paper suggests a method (NoBackTrack) for training recurrent neural networks in an online way, i.e. without having to do backprop th

leetcode N-Queens/N-Queens II, backtracking, C++

thanks to the video of stanford cs106b lecture 10 by Julie Zelenski for the nice explanation of recursion and backtracking, highly recommended. //N-Queens(12ms) class Solution { vector<vector<string>> ans; int N; //int numofsol; void AddTo_ans

Leetcode总结之Backtracking

本文我们就Leetcode中的一个类型的题目backtracking进行一系列的总结和归纳.backtracking这个方法本质是建立在递归的基础上,不断尝试新的路径,这里关键是每次尝试完以后需要退回来也就是回溯. 如果你已经找到了解决方案,那么返回成功 for(现在位置可以的所有可能选择){ 选择其中一个方案然后沿着路径前进一步 使用递归的方法从新的位置解决问题 如果新的位置可以成功解决,向上一级返回成功 从现在位置恢复到循环之前的位置 } 如果到这里表示仍然没有成功,返回失败 下面我们来看一

迷宫问题(MazePath)的求解——利用回溯法(backtracking)

迷宫问题(MazePath)的求解--利用回溯法(backtracking) 1. 迷宫问题的提法 迷宫问题是典型的图的搜索问题. 假设一个迷宫,只有一个入口和一个出口.如果从迷宫的入口到达出口,途中不出现行进方向错误,则得到一条最佳路线. 为此,用一个二维数组maze[m][p]来表示迷宫. (1)当数组元素maze[i][j]=1 (0≤i≤m-1,1≤j≤p-1),表示该位置是墙壁,不能通行. (2)当数组元素maze[i][j]=0 (0≤i≤m-1,1≤j≤p-1),表示该位置是通路,