聊聊一个面试中经常出现的算法题:组合运算及其实际应用例子

简介: 聊聊一个面试中经常出现的算法题:组合运算及其实际应用例子

前言

组合运算是一个数据概念,具体来说,组合运算就是从给定元素集合中选择特定数量的元素进行运算,而不考虑元素的顺序,关注的是哪些元素被选中,而不关心它们的排列顺序。

比如,有一个整数数组 int[] numbers = { 1, 2, 3},它的所有组合就是:

1
2
3
1,2
1,3
2,3
1,2,3

简单例子:列出一个整数数组 int[] numbers = { 1, 2, 3, 4 } 的所有组合

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4 };

        List<List<int>> combinations = GenerateCombinations(numbers);

        foreach (var combination in combinations)
        {
            Console.WriteLine(string.Join(", ", combination));
        }
    }

    static List<List<int>> GenerateCombinations(int[] numbers)
    {
        List<List<int>> result = new List<List<int>>();

        for (int i = 1; i <= numbers.Length; i++)
        {
            GenerateCombinationsUtil(numbers, i, 0, new List<int>(), result);
        }

        return result;
    }

    static void GenerateCombinationsUtil(int[] numbers, int k, int start, List<int> currentCombination, List<List<int>> result)
    {
        if (k == 0)
        {
            result.Add(new List<int>(currentCombination));
            return;
        }

        for (int i = start; i < numbers.Length; i++)
        {
            currentCombination.Add(numbers[i]);
            GenerateCombinationsUtil(numbers, k - 1, i + 1, currentCombination, result);
            currentCombination.RemoveAt(currentCombination.Count - 1);
        }
    }
}

运行后以上代码会生成整数数组 { 1, 2, 3, 4 } 的所有可能组合,并将这些组合打印到控制台。

进阶一:根据需要打印出数组的组合

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4 };
        int k = 2; // 选择的元素数量

        List<List<int>> combinations = GenerateCombinations(numbers, k);

        foreach (var combination in combinations)
        {
            Console.WriteLine(string.Join(", ", combination));
        }
    }

    static List<List<int>> GenerateCombinations(int[] numbers, int k)
    {
        List<List<int>> result = new List<List<int>>();
        List<int> currentCombination = new List<int>();

        GenerateCombinationsHelper(numbers, k, 0, 0, currentCombination, result);

        return result;
    }

    static void GenerateCombinationsHelper(int[] numbers, int k, int start, int currentSize, List<int> currentCombination, List<List<int>> result)
    {
        if (currentSize == k)
        {
            result.Add(new List<int>(currentCombination));
            return;
        }

        for (int i = start; i < numbers.Length; i++)
        {
            currentCombination.Add(numbers[i]);
            GenerateCombinationsHelper(numbers, k, i + 1, currentSize + 1, currentCombination, result);
            currentCombination.RemoveAt(currentCombination.Count - 1);
        }
    }
}

进阶二:排列出集合的组合,所进行运算

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main()
    {
    // 创建集合
        List<Item> itemsList = new List<Item>
    {
      new Item { Number = 1, Amount = 100 },
      new Item { Number = 2, Amount = 200 },
      new Item { Number = 3, Amount = 300 }
    };
    
    // 进行组合
    List<List<Item>> combinations = GenerateCombinations(itemsList);

    // 对组合结果进行运算
    StringBuilder sb = new StringBuilder(1024);
    foreach (var combination in combinations)
    {
      for (var i = 0; i < combination.Count; i++)
      {
        var item = combination[i];
        sb.Append(item.Number);
        if (i < combination.Count - 1)
        {
          sb.Append(" + ");
        }
      }
      var cash = combination.Sum(x => x.Amount);
      sb.AppendLine($" = {cash}");
    }
    
    // 打印结果
    Console.WriteLine(sb.ToString());
    }

    static List<List<Item>> GenerateCombinations(List<Item> numbers)
  {
    List<List<Item>> result = new List<List<Item>>();

    // 从 2 个元素开始进行组合
    for (int i=2; i <= numbers.Count; i++)
    {
      GenerateCombinationsHelper(numbers, i, 0, new List<Item>(), result);
    }

    return result;
  }

    static GenerateCombinationsHelper(List<Item> numbers, int k, int start, List<Item> currentCombination, List<List<Item>> result)
  {
    if (k == 0)
    {
      result.Add(new List<Item>(currentCombination));
      return;
    }

    for (int i = start; i < numbers.Count; i++)
    {
      currentCombination.Add(numbers[i]);
      GenerateCombinationsHelper(numbers, k - 1, i + 1, currentCombination, result);
      currentCombination.RemoveAt(currentCombination.Count - 1);
    }
  }
}

// 定义集合元素类
class Item
{
  // 编号
    public int Number { get; set; }
  
  // 金额
    public decimal Amount { get; set; }
}

总结

组合运算是面试中经常被问到的一个算法题,在实际业务中也会经常使用,希望以上例子对你有所帮助。

我是老杨,一个奋斗在一线的资深研发老鸟,让我们一起聊聊技术,聊聊人生。

都看到这了,求个点赞、关注、在看三连呗,感谢支持。


相关文章
|
2月前
|
存储 监控 JavaScript
基于布隆过滤器的 Node.js 算法在局域网电脑桌面监控设备快速校验中的应用研究
本文探讨了布隆过滤器在局域网电脑桌面监控中的应用,分析其高效空间利用率、快速查询性能及动态扩容优势,并设计了基于MAC地址的校验模型,提供Node.js实现代码,适用于设备准入控制与重复数据过滤场景。
70 0
|
13天前
|
机器学习/深度学习 资源调度 算法
遗传算法模型深度解析与实战应用
摘要 遗传算法(GA)作为一种受生物进化启发的优化算法,在复杂问题求解中展现出独特优势。本文系统介绍了GA的核心理论、实现细节和应用经验。算法通过模拟自然选择机制,利用选择、交叉、变异三大操作在解空间中进行全局搜索。与梯度下降等传统方法相比,GA不依赖目标函数的连续性或可微性,特别适合处理离散优化、多目标优化等复杂问题。文中详细阐述了染色体编码、适应度函数设计、遗传操作实现等关键技术,并提供了Python代码实现示例。实践表明,GA的成功应用关键在于平衡探索与开发,通过精心调参维持种群多样性同时确保收敛效率
|
13天前
|
机器学习/深度学习 边缘计算 人工智能
粒子群算法模型深度解析与实战应用
蒋星熠Jaxonic是一位深耕智能优化算法领域多年的技术探索者,专注于粒子群优化(PSO)算法的研究与应用。他深入剖析了PSO的数学模型、核心公式及实现方法,并通过大量实践验证了其在神经网络优化、工程设计等复杂问题上的卓越性能。本文全面展示了PSO的理论基础、改进策略与前沿发展方向,为读者提供了一份详尽的技术指南。
粒子群算法模型深度解析与实战应用
|
13天前
|
机器学习/深度学习 算法 安全
小场景大市场:猫狗识别算法在宠物智能设备中的应用
将猫狗识别算法应用于宠物智能设备,是AIoT领域的重要垂直场景。本文从核心技术、应用场景、挑战与趋势四个方面,全面解析这一融合算法、硬件与用户体验的系统工程。
|
3月前
|
机器学习/深度学习 人工智能 算法
AI-Compass 强化学习模块:理论到实战完整RL技术生态,涵盖10+主流框架、多智能体算法、游戏AI与金融量化应用
AI-Compass 强化学习模块:理论到实战完整RL技术生态,涵盖10+主流框架、多智能体算法、游戏AI与金融量化应用
|
3月前
|
机器学习/深度学习 人工智能 自然语言处理
深度学习模型、算法与应用的全方位解析
深度学习,作为人工智能(AI)的一个重要分支,已经在多个领域产生了革命性的影响。从图像识别到自然语言处理,从语音识别到自动驾驶,深度学习无处不在。本篇博客将深入探讨深度学习的模型、算法及其在各个领域的应用。
464 3
|
3月前
|
存储 监控 安全
企业上网监控系统中红黑树数据结构的 Python 算法实现与应用研究
企业上网监控系统需高效处理海量数据,传统数据结构存在性能瓶颈。红黑树通过自平衡机制,确保查找、插入、删除操作的时间复杂度稳定在 O(log n),适用于网络记录存储、设备信息维护及安全事件排序等场景。本文分析红黑树的理论基础、应用场景及 Python 实现,并探讨其在企业监控系统中的实践价值,提升系统性能与稳定性。
71 1
|
2月前
|
算法 数据可视化
matlab版本粒子群算法(PSO)在路径规划中的应用
matlab版本粒子群算法(PSO)在路径规划中的应用
|
3月前
|
存储 监控 算法
公司员工泄密防护体系中跳表数据结构及其 Go 语言算法的应用研究
在数字化办公中,企业面临员工泄密风险。本文探讨使用跳表(Skip List)数据结构优化泄密防护系统,提升敏感数据监测效率。跳表以其高效的动态数据处理能力,为企业信息安全管理提供了可靠技术支持。
56 0

热门文章

最新文章