经典算法题之子集(四)

方法二:回溯

算法

幂集是所有长度从 0 到 n 所有子集的组合。

根据定义,该问题可以看作是从序列中生成幂集。

遍历 子集长度,通过 回溯 生成所有给定长度的子集。

回溯法是一种探索所有潜在可能性找到解决方案的算法。如果当前方案不是正确的解决方案,或者不是最后一个正确的解决方案,则回溯法通过修改上一步的值继续寻找解决方案。

算法

定义一个回溯方法 backtrack(first, curr),第一个参数为索引 first,第二个参数为当前子集 curr。

  • 如果当前子集构造完成,将它添加到输出集合中。
  • 否则,从 first 到 n 遍历索引 i。
  • 将整数 nums[i] 添加到当前子集 curr。
  • 继续向子集中添加整数:backtrack(i + 1, curr)。
  • 从 curr 中删除 nums[i] 进行回溯。

Python 实现

复制代码
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def backtrack(first = 0, curr = []):
            # if the combination is done
            if len(curr) == k:  
                output.append(curr[:])
            for i in range(first, n):
                # add nums[i] into the current combination
                curr.append(nums[i])
                # use next integers to complete the combination
                backtrack(i + 1, curr)
                # backtrack
                curr.pop()
        
        output = []
        n = len(nums)
        for k in range(n + 1):
            backtrack()
        return output

Java 实现

复制代码
class Solution {
  List<List<Integer>> output = new ArrayList();
  int n, k;

  public void backtrack(int first, ArrayList<Integer> curr, int[] nums) {
    // if the combination is done
    if (curr.size() == k)
      output.add(new ArrayList(curr));

    for (int i = first; i < n; ++i) {
      // add i into the current combination
      curr.add(nums[i]);
      // use next integers to complete the combination
      backtrack(i + 1, curr, nums);
      // backtrack
      curr.remove(curr.size() - 1);
    }
  }

  public List<List<Integer>> subsets(int[] nums) {
    n = nums.length;
    for (k = 0; k < n + 1; ++k) {
      backtrack(0, new ArrayList<Integer>(), nums);
    }
    return output;
  }
}

复杂度分析

相关推荐
心中有国也有家1 天前
cann-recipes-infer:昇腾 NPU 推理的“菜谱集合”
经验分享·笔记·学习·算法
绝知此事1 天前
【算法突围 01】线性结构与哈希表:后端开发的收纳术
java·数据结构·算法·面试·jdk·散列表
碧海银沙音频科技研究院1 天前
通话AEC与语音识别AEC的软硬回采链路
深度学习·算法·语音识别
csdn_aspnet1 天前
Python 算法快闪 LeetCode 编号 70 - 爬楼梯
python·算法·leetcode·职场和发展
m0_629494731 天前
LeetCode 热题 100-----26.环形链表 II
数据结构·算法·leetcode·链表
壹号用户1 天前
用队列实现栈
数据结构·算法
做人求其滴1 天前
面试经典 150 题 380 274
c++·算法·面试·职场和发展·力扣
daad7771 天前
记一组无人机IMU传感器数据
算法
计算机安禾1 天前
【c++面向对象编程】第42篇:模板特化与偏特化:为特定类型定制实现
开发语言·c++·算法