赞
踩
关于回溯的练习:
- class Solution {
- public:
- vector<vector<int>> paths;
- vector<int> path;
- void backtracking(int n, int k, int startIndex) {
- if(path.size()==k) {
- paths.push_back(path);
- return;
- }
- for(int i=startIndex; i<=n; ++i) {
- path.push_back(i);
- backtracking(n, k, i+1);
- path.pop_back();
- }
-
- }
-
- vector<vector<int>> combine(int n, int k) {
- backtracking(n, k, 1);
- return paths;
-
- }
- };
- class Solution {
- public:
- // 合为n 1-9个数 k个选择
- vector<vector<int>> paths;
- vector<int> path;
- void backtracking(int n, int k, int curSum, int startIndex) {
- if(curSum>n) {
- return;
- }
-
- if(path.size()==k) {
- if(curSum==n)
- paths.push_back(path);
- return;
- }
- for(int i=startIndex; i<=9; ++i) {
- curSum += i;
- path.push_back(i);
- backtracking(n, k, curSum, i+1);
- curSum -= i;
- path.pop_back();
- }
-
- }
-
- vector<vector<int>> combinationSum3(int k, int n) {
- backtracking(n, k, 0, 1);
- return paths;
- }
- };
- class Solution {
- public:
- // 第startIndex个字符 总长度 digits.size()
- vector<string> paths;
- string path;
- vector<string> myvect = {
- "",
- "",
- "abc",
- "def",
- "ghi",
- "jkl",
- "mno",
- "pqrs",
- "tuv",
- "wxyz"
- };
-
- void backtracking(string& digits, int startIndex) {
- if(path.size()==digits.size()) {
- paths.push_back(path);
- return;
- }
- int index = digits[startIndex] - '0';
- string first = myvect[index];
-
- for(int i=0; i<first.size(); ++i) {
- path.push_back(first[i]);
- backtracking(digits, startIndex+1);
- path.pop_back();
- }
-
- }
-
- vector<string> letterCombinations(string digits) {
- if(digits.size()==0) {
- return {};
- }
-
- backtracking(digits, 0);
- return paths;
- }
- };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。