leetcode回溯算法(backtracking)总结

算法导论之P、NP、NPC问题 P、NP、NPC概念 > P问题:能够在多项式时间内解决的决策问题。 —举例: 图搜索问题、最短路径问题、最小生成树问题······ > NP问题:不能在多项式时间内解决或不确定能不能在多项式时间内解决,但能在多项式时间验证的问题。 —验证:给定一个问题的实例、证书(类似于证据),需要验证这个证书是这个问题的正确答案。 — 举例:汉密尔顿路径,实例为G=(V,E) 阅读详情

回溯算法的定义:回溯算法也叫试探法,它是一种系统地搜索问题的解的方法。回溯算法的基本思想是:从一条路往前走,能进则进,不能进则退回来,换一条路再试。

回溯算法实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就“回溯”返回,尝试别的路径。回溯法是一种选优搜索法,按选优条件向前搜索,以达到目标。但当探索到某一步时,发现原先选择并不优或达不到目标,就退回一步重新选择,这种走不通就退回再走的技术为回溯法。适用于求解组合数较大的问题。

对于回溯问题,总结出一个递归函数模板,包括以下三点

  • 递归函数的开头写好跳出条件,满足条件才将当前结果加入总结果中
  • 已经拿过的数不再拿 if(s.contains(num)){continue;}
  • 遍历过当前节点后,为了回溯到上一步,要去掉已经加入到结果list中的当前节点。

针对不同的题目采用不同的跳出条件或判断条件。

下面通过几个例子来说明对上述模板的使用

46. Permutations

Given a collection of distinct integers, return all possible permutations.

Example:

Input: [1,2,3]
Output:
[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]
数组中数的全排列,其中数组中不包含重复元素。
public List<List<Integer>> permute(int[] nums) {
   List<List<Integer>> list = new ArrayList<>();
   backtracking(list, new ArrayList<>(), nums);
   return list;
}

private void backtracking(List<List<Integer>> list, List<Integer> tempList, int [] nums){
   if(tempList.size() == nums.length){  //已将全部数选出,满足条件加入结果集,结束递归
      list.add(new ArrayList<>(tempList));
   } else{
      for(int i = 0; i < nums.length; i++){ 
         if(tempList.contains(nums[i])) continue; // 已经选过的数不再选
         tempList.add(nums[i]);  //选择当前节点
         backtracking(list, tempList, nums);  //递归
         tempList.remove(tempList.size() - 1); //回溯到上一步,去掉当前节点
      }
   }
} 

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]
在上一题的基础上,数组中包含重复元素,加入boolean数组判断当前节点是否已被选过,先对数组进行排序,使重复数字相邻。修改判断条件使相同的排列只出现一次。
public List<List<Integer>> permuteUnique(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        backtracking(ret,new ArrayList<>(),nums,new boolean[nums.length]);
        return ret;
    }
    
    public void backtracking(List<List<Integer>> ret,List<Integer> list,int[] nums,boolean[] used) {
        if(list.size()==nums.length) {
            ret.add(new ArrayList<>(list));
            return;
        }
        for(int i=0;i<nums.length;i++) {
            //重复元素只按顺序选择,若当前元素未被选择且前一元素与当前元素值相等也未被选择则跳过,这一可能情况与先选小序号后选大序号的相同元素相同
            if(used[i] || i>0 && nums[i]==nums[i-1] && !used[i-1]) continue;
            used[i]=true;
            list.add(nums[i]); //选择当前点
            backtracking(ret,list,nums,used); //递归
            used[i]=false;
            list.remove(list.size()-1); //回溯到上一步,去掉当前节点
        }
    }

39. Combination Sum

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

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

Note:

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

Example 1:

Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
  [7],
  [2,2,3]
]

Example 2:

Input: candidates = [2,3,5], target = 8,
A solution set is:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]
public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        backtracking(ret,new ArrayList<>(),candidates,target);
        return ret;
    }
    
    public void backtracking(List<List<Integer>> ret,List<Integer> list,int[] candidates,int target) {
        if(target<0) return;
        else if(target==0) ret.add(new ArrayList<>(list));
        else {
            for(int i=0;i<candidates.length;i++) {
                list.add(candidates[i]);
                backtracking(ret,list,candidates,target-candidates[i]);
                list.remove(list.size()-1);
            }
        }
    }
组合数使其和=target,一开始没有考虑选择顺序,导致了重复答案的出现,
Your answer
[[2,2,3],[2,3,2],[3,2,2],[7]]
Expected answer
[[2,2,3],[7]]






原因在于没有按顺序选择数字,先选前面再选后面与先选后面再选前面得到了一样的答案。为了按顺序选择,加入一个position记录当前选的到的位置。
修正如下,每次只选择当前已选到位置或其之后的位置,则不会出现重复答案。
public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        backtracking(ret,new ArrayList<>(),candidates,target,0);
        return ret;
    }
    
    public void backtracking(List<List<Integer>> ret,List<Integer> list,int[] candidates,int target,int position) {
        if(target<0) return;
        else if(target==0) ret.add(new ArrayList<>(list));
        else {
            for(int i=position;i<candidates.length;i++) {
                list.add(candidates[i]);
                backtracking(ret,list,candidates,target-candidates[i],i);
                list.remove(list.size()-1);
            }
        }
    }

40. Combination Sum II

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

Each number in candidates 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.

Example 1:

Input: candidates = [10,1,2,7,6,1,5], target = 8,
A solution set is:
[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

Example 2:

Input: candidates = [2,5,2,1,2], target = 5,
A solution set is:
[
  [1,2,2],
  [5]
]
在上一题的基础上一个元素只能使用一次,即将position改为当前的下一位避免重复选择。这一题中数组中有重复元素,为了消除重复元素导致答案重复,添加判断条件。
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(candidates);
        backtracking(ret,new ArrayList<>(),candidates,target,0);
        return ret;
    }
    
    public void backtracking(List<List<Integer>> ret,List<Integer> list,int[] candidates,int target,int position) {
        if(target<0) return;
        else if(target==0) ret.add(new ArrayList<>(list));
        else {
            for(int i=position;i<candidates.length;i++) {
                if(i>position&&candidates[i]==candidates[i-1]) continue; //当i位置与前一位置数字相同,再次选择i会导致重复答案
                list.add(candidates[i]);
                backtracking(ret,list,candidates,target-candidates[i],i+1); //从当前位的下一位开始
                list.remove(list.size()-1);
            }
        }
    }

216. Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Note:

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

Example 1:

Input: k = 3, n = 7
Output: [[1,2,4]]

Example 2:

Input: k = 3, n = 9
Output: [[1,2,6], [1,3,5], [2,3,4]]
1-9中k个数的和为n,且不允许重复选择,只是在二的基础上将candidates数组改为1-9,本质上是相同的。
public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ret = new ArrayList<>();
        backtracking(ret,new ArrayList<>(),k,n,1);
        return ret;
    }
    
    public void backtracking(List<List<Integer>> ret,List<Integer> list,int k,int n,int position) {
        if(n<0||list.size()>k) return;
        else if(n==0&&list.size()==k) ret.add(new ArrayList<>(list));
        else {
            for(int i=position;i<10;i++) {
                list.add(i);
                backtracking(ret,list,k,n-i,i+1);
                list.remove(list.size()-1);
            }
        }
    }

78. Subsets

Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: nums = [1,2,3]
Output:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]
求子集,本题没有满足条件加入结果集,而是每次都将其加入结果集。子集也需按位置序选择以避免出现重复答案,与上述思路相同。
public List<List<Integer>> subsets(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        backtracking(ret,new ArrayList<>(),nums,0);
        return ret;
    }
    
    public void backtracking(List<List<Integer>> ret,List<Integer> list,int[] nums,int position) {
        ret.add(new ArrayList<>(list));  //每次递归将其加入结果集
        for(int i=position;i<nums.length;i++) {
            list.add(nums[i]);
            backtracking(ret,list,nums,i+1); //从当前位置的下一位置开始选择
            list.remove(list.size()-1);
        }
    }

90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

Input: [1,2,2]
Output:
[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]
在上一题的基础上加入重复元素,与求和问题类似,为了避免相同元素带来的重复答案,对数组排序,加入判断条件,只选择第一个遇到的重复元素。
public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> ret = new ArrayList<>();
        Arrays.sort(nums);
        backtracking(ret,new ArrayList<>(),nums,0);
        return ret;
    }
    
    public void backtracking(List<List<Integer>> ret,List<Integer> list,int[] nums,int position) {
        ret.add(new ArrayList<>(list));  
        for(int i=position;i<nums.length;i++) {
            if(i>position&&nums[i]==nums[i-1]) continue;
            list.add(nums[i]);
            backtracking(ret,list,nums,i+1); 
            list.remove(list.size()-1);
        }
    }
以及经典的n皇后问题,在任意一个皇后所在位置的水平、竖直、45度斜线上不能出现皇后的棋子。n皇后放置完毕后绘制棋盘。
if(legal(pos,i,j)) { //判断皇后是否合法
 pos[i][j]=true;
 backtracking(ret,pos,n-1,i+1,0);  //递归
 pos[i][j]=false; //回溯
}
该文从以下两链接处获得思路,可供参考

Leetcode - 回溯算法(Backtracking)解题模板 回溯算法(Backtracking)的使用场景主要是解决排列组合问题,这类问题的共性就是需要穷举所有的可能/组合,这也意味在不做优化的情况下,需要遍历所有的情况,这也决定了回溯算法无论怎样优化,复杂度都是O(N!) 阅读详情

相关推荐

Mac上安装虚拟机搭载window系统

用Mac的都知道,很多window用的软件是Mac版本没有的。平时有的还得要求去用那些软件,有几种方式可供大家选择: 1.再买个window本; 2.装双系统; 3.装虚拟机,搭载window系统。 我比较推荐第3条,这样可以在Mac本上做到双开,一边开着mac一边开着window,还能做到同时处理文件,不至于重新启动操作系统,下边是具体实现步骤,其中有几个需要下载的,建议在网速好的时候完...

Coder_Mumu的博客 1万+

P问题、NP问题、NPC问题(NP完全问题)、NPH问题和多项式时间复杂度

转自 http://blog.csdn.net/k346k346/article/details/51026006 本文为博主吕吕(Dablelv)原创文章,欢迎转载,传播知识,请留言告知并注明出处。个人之言,请抱着怀疑的态度参考! 目录(?)[+] 为了弄清楚上面的概念以及对他们有个基本的了解,所以总结出这篇blog。 1.多项式时间复杂度

knightmarehs的专栏 4986

VS Code + EIDE + Clangd 构建 Keil/MDK 嵌入式开发新范式

嵌入式C/C++开发长期受限于传统IDE的语法理解弱、导航卡顿、跨工程复用难等问题。Clangd作为基于AST的现代语言服务器,结合EIDE对Keil uVision和ARM MDK工程文件(.uvprojx)的深度解析能力,可将编译配置、芯片型号、内存模型、扩展关键字等语义精准翻译为标准compile_commands.json,从而实现智能跳转、宏展开识别、结构体实时展开等高阶编辑体验。该方案不替换Keil/MDK编译与烧录流程,仅升级代码理解层,天然兼容STC8051、STM32 Cortex-M、G

weixin_34321753的博客 360

【回溯算法 backtracking】

目录什么是回溯算法???从全排列问题开始理解回溯搜索算法总结回溯算法基础问题列表 什么是回溯算法??? 回溯算法(backtracking)是暴力搜索算法的一种。 这句话向我们揭示了回溯算法的用途:搜索,因此回溯算法也被称为回溯搜索算法。与“二分查找”、“线性查找”等“查找问题”不同的是,“搜索问题”完成一件事情有可能多种方法,而每一种方法又有多个步骤,回溯算法就是在不断尝试,以得到待求问题的...

zj20165149的博客 1625

WIFI 相关的频偏调试以及天线调试记录

WIFI RF 相关的频偏调试以及天线调试 1,频率误差(Frequency Error) 频率误差(Frequency Error):表征射频信号偏离该信号所处信道中心频率的大小,单位PPM。频偏误差要求范围如下表。 频偏越小越好。PPM的计算公式如下: 问题: 我们ESP8089认证测试的时候频偏测试超了。需要修改哪些呢。 测试频率点在2.411865385GHz 宣称点:2.412GHz 频率偏移计算:{(2.412GHz-2.411865385GHz)÷2...

armkits的博客 1万+

vscode中创建vue快捷键

1.安装Vetur插件(扩展里面直接搜) 2.vscode 界面里面左上角选则 文件=> 首选项=> 用户代码片段=>新建全局代码片段=>在输入框中新建名称为vue.json 3.删除里面的注释,当然你也可以留着,把下面的代码粘贴进去! { // Place your 全局 snippets here. Each snippet is defined under a snippet name and has a scope, prefix, body and // descri

Leon_940002463的博客 3215

LeetCode算法之----回溯

回溯算法

程序大视界 1406

学习笔记9--智能驾驶的功能安全设计之功能安全设计

本系列博客包括6个专栏,分别为:《自动驾驶技术概览》、《自动驾驶汽车平台技术基础》、《自动驾驶汽车定位技术》、《自动驾驶汽车环境感知》、《自动驾驶汽车决策与控制》、《自动驾驶系统设计及应用》。此专栏是关于《自动驾驶系统设计及应用》书籍的笔记.

FUXI_Willard 1805

Leetcode刷题笔记:回溯篇

Leetcode刷题笔记:回溯篇

qq_27673853的博客 603

多跳问答技术解析:从原理到金融领域实践

多跳问答(Multi-hop QA)是自然语言处理中的高级任务,要求系统通过多步推理整合分散信息来回答问题。其核心技术在于理解文档间的复杂关联,相比单跳问答需要更精细的数据集设计和模型架构。在金融、医疗等专业领域,多跳问答能有效处理如'腾讯大股东投资的港股上市公司'这类需要串联多个信息点的问题。典型实现方案包括MR-Search框架的三级检索器设计,分别处理实体召回、关系匹配和数值比较。当前最佳实践表明,结合稠密检索与稀疏检索的混合策略,配合动态路由机制,能在保持较高精度的同时控制计算成本。这类技术在金融风

weixin_42566072的博客 607

实战六十四:基于机器学习朴素贝叶斯的豆瓣Top250影评的情感分析与预测 附完整源码和数据

实战六十四:基于机器学习朴素贝叶斯的豆瓣Top250影评的情感分析与预测 附完整源码和数据

1574

backtracking Leetcode 回溯算法题

第一个位置选择有 n 种,接下来每个位置只能在前面选择数字的后面选,所以有了 beg 参数,才能保持不重复剪枝:res.size + (n - beg + 1) < k , 已有答案的长度 + 剩余所有未选择的个数 都小于最终答案长度了 就没有必要尝试下去。

xiongyuqing的博客 752

3dmax文件格式转换——.max 转换为 .flt(解决转换后.flt没有纹理贴图的问题)

本文主要介绍如何在3dmax中将.max格式文件转换为.flt格式文件,并解决转换后的文件没有纹理贴图的问题。 在3dmax中,将.max文件转换为.flt格式,只需导出选择.flt格式即可,但是导出的文件在osgEarth中加载后,缺少纹理和贴图。 下面是解决方案: 1、选中加载的模型,然后点击 渲染-> 渲染到纹理 2、将 渲染到纹理 子窗口往下拉,点击 添加 按钮,添加 ...

cchangcs 6192

LeetCode 回溯算法 backtracking

1. Sudoku Solver rite a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by the character '.'. You may assume that there will be only one unique soluti

coder 进阶的专栏 2462

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

掌握回溯算法(Backtracking):从 LeetCode 到实际应用

回溯是一种问题求解技术,它通过逐步构建候选解的方式来探索所有可能的解决方案,并在确定当前候选解无法导向有效解时立刻放弃该路径。

2401_89221445的博客 940

温度PID控制PLC程序

温度PID稳定控制程序,适用于欧姆龙PLC,对其他PLC也具有很大参考价值

回溯算法1:组合

【代码】回溯算法1:组合。

m0_74201718的博客 183

Leetcode Backtracking(回溯算法) 刷题笔记

78. Subsets 该题给我们一个array,要求我们找到所有不重复的子集 输入: nums = [1,2,3] 输出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ] 复制代码这里我们运用backtracking算法,先sort array在此题中其实并无意义,建立一个backtrack方法,在方法中,先...

weixin_34381666的博客 250

复习backtracking 并总结

每一个分支把leetcode backtracking 几十个题目重新复习一遍,领略back tracking 精髓。 一 排列问题: 46/47 Permutations : 46 没有重复数字 47 包含重复数字 46: 关键是采用used[i] 来标记一个i 是否已经被选择了, 注意used 状态改变只对子节点状态有效,对 同一层的节点状态是无效的,这也是back t...

apma88030的博客 345

算法训练营第24天|回溯算法理论基础 LeetCode 77.组合

回溯叫做回溯搜索法,是一种搜索方式。回溯是递归的副产品,有递归就会有回溯。

qq_53125539的博客 303

leetcode题解77:组合(回溯算法的门面)

本文介绍了使用回溯算法解决组合问题的思路。给定整数n和k,要求在1到n范围内生成所有可能的k个数组合。通过递归函数backtracking实现:当路径长度等于k时保存结果;否则从startindex开始逐个添加数字,递归处理i+1位置的数字,并在回溯时移除当前数字。示例展示了n=4、k=2时的完整递归过程,最终生成所有有效组合。该方法通过递归分解问题,利用回溯恢复状态,确保正确生成所有不重复的组合。

2301_80548884的博客 1045

回溯算法——切割问题(力扣93:复原IP地址)

有效 IP 地址 正好由四个整数(每个整数位于 0 到 255 之间组成,且不能含有前导 0),整数之间用 '.' 分隔。例如:"0.1.2.201" 和 "192.168.1.1" 是 有效 IP 地址,但是 "0.011.255.245"、"192.168.1.312" 和 "192.168@1.1" 是 无效 IP 地址。给定一个只包含数字的字符串 s ,用以表示一个 IP 地址,返回所有可能的有效 IP 地址,这些地址可以通过在 s 中插入'.' 来形成。你不能重新排序或删除 s 中的任何数字

qq_40472852的博客 1753

LeetCode 17 电话号码的字母组合(字符串、回溯算法Backtracking、递归Recursive)

题目要求: 给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。 给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。 示例: 输入:"23" 输出:["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"]. 说

volcano_Lin 的博客 904

LeetCode-77-组合-回溯算法

① 确定递归函数的参数和返回值;一般是 void,名字一般是 backtracking。③ 确定单层递归逻辑。

Arbicoral的博客 208

Leetcode算法训练日记 | day29

Leetcode:第 491 题 给你一个整数数组nums,找出并返回所有该数组中不同的递增子序列,递增子序列中至少有两个元素。你可以按任意顺序返回答案。数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。 Leetcode:第 46题 给定一个不含重复数字的数组nums,返回其所有可能的全排列。你可以按任意顺序返回答案。 Leetcode:第 47题 给定一个可包含重复数字的序列nums,按任意顺序返回所有不重复的全排列。

m0_74882777的博客 1241

代码随想录算法训练营Day24|77. 组合

【代码】代码随想录算法训练营Day24|77. 组合。

Magical_Jasen的博客 744

回溯算法part05 算法

今日任务。

Belle_Daisy的博客 637
上一篇: leetcode排序总结
下一篇: 通俗易懂的傅里叶变换讲解(多图预警)
wonner_
博客等级 码龄9年 49粉丝 22原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值