呜呜呜 递归好不想写qwq

求“所有情况”这种就递归

17. Letter Combinations of a Phone Number

题意:在九宫格上按数字,输出所有可能的字母组合

Input: ""
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].

思路:递归回溯求解

递归保存的是每层的状态,因此每层的 str 不应该改,而是更改str和idx后进入到下一层

class Solution {
public:
vector<string> letterCombinations(string digits) {
int n = digits.length();
if (n == ) return {};
vector<string> ans;
string dict[] = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
dfs("", , dict, n, digits, ans);
return ans;
}
void dfs(string str, int idx, string dict[], int n, string digits, vector<string> &ans) {
if (idx == n) {
ans.push_back(str);
return;
}
if (digits[idx] <= '' || digits[idx] > '') return;
for (int i = ; i < dict[digits[idx] - ''].length(); i++) {
//str += dict[digits[idx] - '0'][i];
dfs(str + dict[digits[idx] - ''][i], idx + , dict, n, digits, ans);
}
}
};

22. Generate Parentheses

题意:n组括号,求搭配情况数

For example, given n = , a solution set is:

[
"((()))",
"(()())",
"(())()",
"()(())",
"()()()"
]

思路:emm递归

快乐 递归函数里记录每层的状态

class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> ans;
dfs(ans, "", , , n);
return ans;
}
void dfs(vector<string> &ans, string str, int cnt1, int cnt2, int n) {
if (cnt1 + cnt2 == n * ) {
ans.push_back(str);
return;
}
if (cnt1 < n) dfs(ans, str + '(', cnt1 + , cnt2, n);
if (cnt2 < cnt1) dfs(ans, str + ')', cnt1, cnt2 + , n);
}
};

37. Sudoku Solver

题意:求解数独

思路:八皇后的思路,在每个'.'的格子里填可能的数字,填好一个往下递归,如果出现这个格子没有可填的就回溯到上一层

呜呜呜

class Solution {
public:
void solveSudoku(vector<vector<char>>& board) {
dfs(board, , );
}
bool dfs (vector<vector<char>>& board, int row, int col) {
if (col == ) {
row++;
col = ;
}
if (row == ) return true;
if (board[row][col] != '.') {
return dfs(board, row, col + );
} else {
for (int i = ; i <= ; i++) {
char x = i + '';
if (check(board, row, col, x)) {
board[row][col] = x;
if (dfs(board, row, col + )) return true;
}
board[row][col] = '.';
}
}
return false;
}
bool check (vector<vector<char>>& board, int row, int col, char val) {
for (int i = ; i < ; i++) {
if (board[row][i] == val && i != col) {
return false;
}
}
for (int i = ; i < ; i++) {
if (board[i][col] == val && i != row) {
return false;
}
}
for (int i = row / * ; i < row / * + ; i++) {
for (int j = col / * ; j < col / * + ; j++) {
if (board[i][j] == val && i != row && j != col) {
return false;
}
}
}
return true;
}
};

39. Combination Sum

题意:给出一组无重复的数,在里面任意取数(每个数可以取无数次),使得数字之和为target,求解所有情况

递归中记录(要继续取数的起始位置,当前取过的数,他们的和)

class Solution {
public:
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
vector<vector<int>> res;
dfs(candidates, , , {}, target, res);
return res;
}
void dfs(vector<int>& candidates, int start, int sum, vector<int> cur, int target, vector<vector<int>>& res) {
for (int i = start; i < candidates.size(); i++) {
if (sum + candidates[i] > target) {
continue;
} else if (sum + candidates[i] == target) {
cur.push_back(candidates[i]);
res.push_back(cur);
cur.pop_back();
continue;
} else {
cur.push_back(candidates[i]);
dfs(candidates, i, sum + candidates[i], cur, target, res);
cur.pop_back();
}
}
}
};

LeetCode || 递归 / 回溯的更多相关文章

  1. [Leetcode] Backtracking回溯法解题思路

    碎碎念: 最近终于开始刷middle的题了,对于我这个小渣渣确实有点难度,经常一两个小时写出一道题来.在开始写的几道题中,发现大神在discuss中用到回溯法(Backtracking)的概率明显增大 ...

  2. 递归回溯 UVa140 Bandwidth宽带

    本题题意:寻找一个排列,在此排序中,带宽的长度最小(带宽是指:任意一点v与其距离最远的且与v有边相连的顶点与v的距离的最大值),若有多个,按照字典序输出最小的哪一个. 解题思路: 方法一:由于题目说结 ...

  3. Leetcode之回溯法专题-216. 组合总和 III(Combination Sum III)

    Leetcode之回溯法专题-216. 组合总和 III(Combination Sum III) 同类题目: Leetcode之回溯法专题-39. 组合总数(Combination Sum) Lee ...

  4. Leetcode之回溯法专题-212. 单词搜索 II(Word Search II)

    Leetcode之回溯法专题-212. 单词搜索 II(Word Search II) 给定一个二维网格 board 和一个字典中的单词列表 words,找出所有同时在二维网格和字典中出现的单词. 单 ...

  5. Leetcode之回溯法专题-131. 分割回文串(Palindrome Partitioning)

    Leetcode之回溯法专题-131. 分割回文串(Palindrome Partitioning) 给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串. 返回 s 所有可能的分割方案. ...

  6. Leetcode之回溯法专题-90. 子集 II(Subsets II)

    Leetcode之回溯法专题-90. 子集 II(Subsets II) 给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 说明:解集不能包含重复的子集. 示例: 输入 ...

  7. Leetcode之回溯法专题-79. 单词搜索(Word Search)

    Leetcode之回溯法专题-79. 单词搜索(Word Search) 给定一个二维网格和一个单词,找出该单词是否存在于网格中. 单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元 ...

  8. Leetcode之回溯法专题-78. 子集(Subsets)

    Leetcode之回溯法专题-78. 子集(Subsets) 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 说明:解集不能包含重复的子集. 示例: 输入: nums = ...

  9. Leetcode之回溯法专题-77. 组合(Combinations)

    Leetcode之回溯法专题-77. 组合(Combinations)   给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合. 示例: 输入: n = 4, k = 2 输 ...

随机推荐

  1. 萌新笔记之堆(heap)

    前言(萌新感想): 以前用STL的queue啊stack啊priority_queue啊,一直很想懂原理,现在终于课上到了priority_queue,还有就是下周期中考,哈哈,所以写几篇blog总结 ...

  2. [Xcode 实际操作]一、博主领进门-(5)检测运行中的模拟器在各个方向上的切换

    目录:[Swift]Xcode实际操作 本文将演示Xcode的设备模拟器在各个方向上的切换和检测. 在项目导航区,打开视图控制器的代码文件[ViewController.swift] 检测运行中的模拟 ...

  3. bzoj1660:[Usaco2006 Nov]badhair乱头发节

    Description 农民John的某 N 头奶牛 (1 <= N <= 80,000) 正在过乱头发节!由于每头牛都 意识到自己凌乱不堪的发型, FJ 希望统计出能够看到其他牛的头发的 ...

  4. mongodb-Configuration

    命令行和配制后文件接口为Mongodb的管理者提供了大量的控制选项.在这篇文章中提供了对于一般应用场景的最佳实践配置. mongod --config /etc/mongod.conf mongod ...

  5. 【aspnetcore】模拟中间件处理请求的管道

    几个核心对象: ApplicationBuilder 就是startup->Configure方法的第一个参数,请求(HttpContext) 就是由这个类来处理的 HttpContext 这个 ...

  6. 090 Subsets II 子集 II

    给定一个可能包含重复整数的列表,返回所有可能的子集(幂集).注意事项:解决方案集不能包含重复的子集.例如,如果 nums = [1,2,2],答案为:[  [2],  [1],  [1,2,2],  ...

  7. 18000 Two String 暴力。——— 读题

    http://acm.scau.edu.cn:8000/uoj/mainMenu.html 18000 Two String 时间限制:1000MS  内存限制:65535K提交次数:0 通过次数:0 ...

  8. 推荐一个VPS

    有日本节点,不贵,用了两个月,感觉不错 http://www.vultr.com/?ref=6847480

  9. BBS项目需求分析及表格创建

    1.项目需求分析 1.登陆功能(基于ajax,图片验证码) 2.注册功能(基于ajax,基于forms验证) 3.博客首页 4.个人站点 5.文章详情 6.点赞,点踩 7.评论 --根评论 --子评论 ...

  10. IE6下png背景不透明——张鑫旭博客读书笔记

    从今天开始跟着大牛张鑫旭的步伐,每天进步一点点 问题:IE6不支持png背景透明或半透明 一.可解决的方法 补充:css滤镜主要是用来实现图像的各种特殊效果.(了解) css滤镜的标识符是“filte ...