Combinations -- 回溯法--力扣101算法题解笔记

6.3Combinations -- 回溯法

题目描述

给定一个整数n和另一个整数k,在1到n中选取k个数组的所有组合方法

输入输出样例

Input : n = 4 , k = 2

Output: \[1 , 2, 1 , 3, 1 , 4, 2 , 3, 2 , 4, 3 , 4 ]

输出的二维数组可以以任意顺序输出

题解

发现了不,基本上所有找组合、排列问题,都用回溯法是较为方便的。

排列回溯是交换位置然后记录,回溯,接着交换。

组合回溯是 是否把当前数字加入到结果中。

cpp 复制代码
#include <vector>
#include <iostream>
using namespace std;

void backtracking(vector<vector<int>>& ans, vector<int>& comb,
    int& count, int pos, int n, int k) {
    if (count == k) {
        ans.push_back(comb);
        return;
    }
    for (int i = pos; i <= n; ++i) {
        comb[count++] = i;  //修改当前节点
        backtracking(ans, comb, count, i + 1, n, k);    //递归子节点
        --count;    //回改当前节点状态
    }
}

vector<vector<int>> combine(int n , int k) {
    vector<vector<int>> ans;
    vector<int> comb(k, 0);
    int count = 0;
    backtracking(ans, comb, count, 1, n, k);
    return ans;
}

int main() {
    int n = 4, k = 2;
    vector<vector<int>> res = combine(n, k);

    cout << "[";
    for (int i = 0; i < res.size(); ++i) {
        if (i > 0) cout << ", ";
        cout << "[" << res[i][0] << ", " 
                    << res[i][1] << "]";
    }
    cout << "]" << endl;

    return 0;
}
相关推荐
凌冰_9 小时前
数据结构 - 时间空间复杂度(一)
数据结构·算法·软件工程
Pniubi10 小时前
力扣2 . 两数相加
算法·leetcode·职场和发展
戴·菲瑜10 小时前
为什么PPO难以做出顶级棋类引擎
算法·博弈论·rl·ppo
在所不辞兄12 小时前
为什么数字孪生驱动的产线标定需要在线更新机制,而不能一次标定后长期沿用?
人工智能·神经网络·其他·算法·机器学习
郝学胜-神的一滴15 小时前
Effective Python 条款36:优雅拼装迭代器与生成器
开发语言·数据结构·人工智能·python·numpy·scikit-learn
AvocadoZeroOneOI17 小时前
B4500 [GESP202603 三级] 凯撒密码 详细解题报告
c++·算法
cjz389918 小时前
双指针技巧:覆盖式双指针(原地覆盖)
算法
console.log('npc')21 小时前
Python 学习教程 · 第4课:数据结构
数据结构·python·学习
橘子131 天前
【高级数据库】关系代数基本概念
算法
电科_银尘1 天前
【大模型算法与工程 15】手写Self-Attention:Q、K、V与缩放点积
算法