LeetCode | 77. Combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

For example,
If n = 4 and k = 2, a solution is:

[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]

Solution

递归回溯,每次对目标的第Index位进行填数,因为求的是排列组合而不是全排列,所以每次只要填比之前更大的数就好,所以用“start”来记录当前填到了哪个数字。加了一个优化来提前终止不可能的尝试(比如剩下的数字不够填满剩下的空位),69 ms AC,速度挺快,排到了前10%。

Code

class Solution {
public:
    void dfs(int Index, int start, int n, int k, vector<int> &temp, vector<vector<int> > &res)//填temp的第Index位,候选数字从start开始
    {
        if(Index == k+1)
        {
            res.push_back(temp);
            temp.pop_back();
            return;
        }

        for(int i=start;i<=n;i++)
        {
            if(n-start+1 < k-Index+1)//剩下的数字不够填了
                break;
            vector<int> tt = temp;
            temp.push_back(i);
            dfs(Index+1, i+1, n, k, temp, res);
            temp = tt;
        }
    }

    vector<vector<int>> combine(int n, int k)
    {
        vector<vector<int> > res;
        vector<int> temp;

        dfs(1, 1, n, k, temp, res);

        return res;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值