代码随想录算法训练营第二十一天|39.组合总和,40.组合总和2,131.分割回文串

文章介绍了如何通过递归算法解决两个问题:一是寻找无重复元素数组中和为目标数的组合,二是将字符串分割成回文子串。涉及到了回溯和深度优先搜索的编程技巧。
摘要由CSDN通过智能技术生成

39.组合总和

40.组合总和2

131.分割回文串

39.组合总和

给你一个 无重复元素 的整数数组 candidates 和一个目标整数 target ,找出 candidates 中可以使数字和为目标数 target 的 所有 不同组合 ,并以列表形式返回。你可以按 任意顺序 返回这些组合。

candidates 中的 同一个 数字可以 无限制重复被选取 。如果至少一个数字的被选数量不同,则两种组合是不同的。 

对于给定的输入,保证和为 target 的不同组合数少于 150 个。

示例 1:

输入:candidates = [2,3,6,7], target = 7
输出:[[2,2,3],[7]]
解释:
2 和 3 可以形成一组候选,2 + 2 + 3 = 7 。注意 2 可以使用多次。
7 也是一个候选, 7 = 7 。
仅有这两种组合。

示例 2:

输入: candidates = [2,3,5]
target = 8
输出: [[2,2,2,2],[2,3,3],[3,5]]

示例 3:

输入: candidates = [2]
target = 1
输出: []

提示:

  • 1 <= candidates.length <= 30
  • 2 <= candidates[i] <= 40
  • candidates 的所有元素 互不相同
  • 1 <= target <= 40

递归函数参数

vector<vector<int>> result;
vector<int> path;
void backtracking(vector<int>& candidates, int target, int sum, int startIndex)

确定终止条件

        if (sum > target) {
                return;
            }
            if (sum == target) {
                result.push_back(path);
                return;
            }

单层递归逻辑

for (int i = startIndex; i < candidates.size(); i++) {
            sum += candidates[i];
            path.push_back(candidates[i]);
            backtracking(candidates, target, sum, i); // 关键点:不用i+1
            sum -= candidates[i];   // 回溯
            path.pop_back();        // 回溯
        }
    }

整体代码

class Solution {
public:
    vector<vector<int>> result;
    vector<int> path;
    void backtracking(vector<int>& candidates, int target, int sum, int startIndex){
        if (sum > target) {
                return;
            }
            if (sum == target) {
                result.push_back(path);
                return;
            }
        for (int i = startIndex; i < candidates.size(); i++) {
            sum += candidates[i];
            path.push_back(candidates[i]);
            backtracking(candidates, target, sum, i); // 关键点:不用i+1了,表示可以重复读取当前的数
            sum -= candidates[i];   // 回溯
            path.pop_back();        // 回溯
        }
    }
    vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
        backtracking(candidates, target, 0, 0);
        return result;
    }
};

python

class Solution:
    def backtracking(self, candidates, target, Sum, startIndex, path, result):
        if Sum > target:
            return
        if Sum == target:
            result.append(path[:])
            return

        for i in range(startIndex, len(candidates)):
            Sum += candidates[i]
            path.append(candidates[i])
            self.backtracking(candidates, target, Sum, i, path, result)  # 不用i+1了,表示可以重复读取当前的数
            Sum -= candidates[i]
            path.pop()
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        self.backtracking(candidates, target, 0, 0, [], result)
        return result

 40.组合总和2

给定一个候选人编号的集合 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的每个数字在每个组合中只能使用 一次 。

注意:解集不能包含重复的组合。 

示例 1:

输入: candidates = [10,1,2,7,6,1,5], target = 8,
输出:
[
[1,1,6],
[1,2,5],
[1,7],
[2,6]
]

示例 2:

输入: candidates = [2,5,2,1,2], target = 5,
输出:
[
[1,2,2],
[5]
]

提示:

  • 1 <= candidates.length <= 100
  • 1 <= candidates[i] <= 50
  • 1 <= target <= 30

定义used数组

此题还需要加一个bool型数组used,用来记录同一树枝上的元素是否使用过。

vector<bool> used(candidates.size(), false);

对candidates内元素进行排序

 sort(candidates.begin(), candidates.end());

递归函数参数

vector<vector<int>> result; 
vector<int> path;          
void backtracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool>& used)

递归终止条件

if (sum > target) { 
    return;
}
if (sum == target) {
    result.push_back(path);
    return;
}

单层递归逻辑

           used[i - 1] == true,说明同一树枝candidates[i - 1]使用过

           used[i - 1] == false,说明同一树层candidates[i - 1]使用过

        for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {

            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
                continue;
            }
            sum += candidates[i];
            path.push_back(candidates[i]);
            used[i] = true;
            backtracking(candidates, target, sum, i + 1, used);
            used[i] = false;
            sum -= candidates[i];
            path.pop_back();
        }

整体代码

class Solution {
public:
    vector<vector<int>> result; 
    vector<int> path;          
    void backtracking(vector<int>& candidates, int target, int sum, int startIndex, vector<bool>& used) {
        if (sum > target) { // 这个条件其实可以省略
            return;
        }
        if (sum == target) {
            result.push_back(path);
            return;
        }
        for (int i = startIndex; i < candidates.size() && sum + candidates[i] <= target; i++) {

            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false) {
                continue;
            }
            sum += candidates[i];
            path.push_back(candidates[i]);
            used[i] = true;
            backtracking(candidates, target, sum, i + 1, used);
            used[i] = false;
            sum -= candidates[i];
            path.pop_back();
        }
    }

    vector<vector<int>> combinationSum2(vector<int>& candidates, int target) {
        vector<bool> used(candidates.size(), false);
        sort(candidates.begin(), candidates.end());
        backtracking(candidates, target, 0, 0, used);
        return result;
    }
};

python

class Solution:
    def backtracking(self, candidates, target, total, startIndex, path, result):
        if total == target:
            result.append(path[:])
            return

        for i in range(startIndex, len(candidates)):
            if i > startIndex and candidates[i] == candidates[i - 1]:
                continue

            if total + candidates[i] > target:
                break

            total += candidates[i]
            path.append(candidates[i])
            self.backtracking(candidates, target, total, i + 1, path, result)
            total -= candidates[i]
            path.pop()
            
    def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        candidates.sort()
        self.backtracking(candidates, target, 0, 0, [], result)
        return result

131.分割回文串

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是 回文串 。返回 s 所有可能的分割方案。

回文串 是正着读和反着读都一样的字符串。

示例 1:

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"
输出:[["a"]]

提示:

  • 1 <= s.length <= 16
  • s 仅由小写英文字母组成

递归函数参数

vector<vector<string>> result;
vector<string> path; 
void backtracking (const string& s, int startIndex)

终止条件

if (startIndex >= s.size()) {
        result.push_back(path);
        return;
    }

单层递归逻辑

    for (int i = startIndex; i < s.size(); i++) {
            if (isPalindrome(s, startIndex, i)) { // 是回文子串
                string str = s.substr(startIndex, i - startIndex + 1);
                path.push_back(str);
            }
            else continue;
            backtracking(s, i + 1); 
            path.pop_back();        // 回溯
        }

判断是否为回文串

    bool isPalindrome(const string& s, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            if (s[i] != s[j]) {
                return false;
            }
        }
        return true;
    }

整体代码

class Solution {
public:
    vector<vector<string>> result;
    vector<string> path; // 放已经回文的子串
    void backtracking (const string& s, int startIndex){
        if (startIndex >= s.size()) {
            result.push_back(path);
            return;
        }
        for (int i = startIndex; i < s.size(); i++) {
            if (isPalindrome(s, startIndex, i)) { // 是回文子串
                string str = s.substr(startIndex, i - startIndex + 1);
                path.push_back(str);
            }
            else continue;
            backtracking(s, i + 1); 
            path.pop_back();        // 回溯
        }
    }

    bool isPalindrome(const string& s, int start, int end) {
        for (int i = start, j = end; i < j; i++, j--) {
            if (s[i] != s[j]) {
                return false;
            }
        }
        return true;
    }

    vector<vector<string>> partition(string s) {
        backtracking(s, 0);
        return result;
    }
};

python

class Solution:
    def __init__(self):
        self.result = []  # 存储所有可能的分割方案
        self.path = []    # 存储当前分割方案中的回文子串

    def backtracking(self, s, startIndex):
        # 如果startIndex到达字符串末尾,说明找到了一种分割方案
        if startIndex >= len(s):
            self.result.append(self.path.copy())
            return
        
        for i in range(startIndex, len(s)):
            # 如果是回文子串,则加入当前路径
            if self.isPalindrome(s, startIndex, i):
                # 截取回文子串
                self.path.append(s[startIndex:i+1])
                # 递归探索剩余子串的分割方案
                self.backtracking(s, i+1)
                # 回溯,撤销上一步的选择
                self.path.pop()

    def isPalindrome(self, s, start, end):
        # 判断子串s[start:end+1]是否为回文
        while start < end:
            if s[start] != s[end]:
                return False
            start, end = start + 1, end - 1
        return True

    def partition(self, s):
        self.backtracking(s, 0)
        return self.result

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值