LeetCode77. Combinations

该篇文章介绍了如何使用C++编程语言中的回溯法(backtracking)解决一个题目,给定两个整数n和k,要求找出所有从1到n中选择k个数的不同组合,组合是无序的。Solution类中定义了一个backTracking函数实现此功能,最后返回所有可能的组合列表。
摘要由CSDN通过智能技术生成

一、题目

Given two integers n and k, return all possible combinations of k numbers chosen from the range [1, n].

You may return the answer in any order.

Example 1:

Input: n = 4, k = 2
Output: [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
Explanation: There are 4 choose 2 = 6 total combinations.
Note that combinations are unordered, i.e., [1,2] and [2,1] are considered to be the same combination.
Example 2:

Input: n = 1, k = 1
Output: [[1]]
Explanation: There is 1 choose 1 = 1 total combination.

Constraints:

1 <= n <= 20
1 <= k <= n

二、题解

class Solution {
public:
    vector<int> tmp;
    vector<vector<int>> res;
    void backTracking(int n,int k,int startIndex){
        if(tmp.size() == k){
            res.push_back(tmp);
            return;
        }
        for(int i = startIndex;i <= n;i++){
            tmp.push_back(i);
            backTracking(n,k,i+1);
            tmp.pop_back();
        }
    }
    vector<vector<int>> combine(int n, int k) {
        backTracking(n,k,1);
        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值