[LeetCode] Combinations

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], ]

题目的意思就是求组合数,注意这道题和求排列数求排列数很相似,所以也可以用回溯法(DFS)

区别就是求组合数的时候,一个数如果使用过了就不要再使用了,下标的起点需要调整下。

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<bool> visited(n+1,false);
        vector<int> curr;
        vector<vector<int>> vv;
        int i =1;
        combinations(n,k,i,vv,curr,visited);
        return vv;

    }

    void combinations(int n, int k, int i, vector<vector<int>> &vv, vector<int> &curr, vector<bool> &visited){
        if(curr.size()==k){
            vv.push_back(curr);
            return;
        }
        for(; i<=n; ++i){
            if(visited[i]==false){
                visited[i]=true;
                curr.push_back(i);
                combinations(n,k,i+1,vv,curr,visited);
                curr.pop_back();
                visited[i]=false;
            }
        }
    }
};

12ms AC

再精炼一下会发现其实visited只是针对于求排列数来说的,

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<int> curr;
        vector<vector<int>> vv;
        int i =1;
        combinations(n,k,i,vv,curr);
        return vv;

    }

    void combinations(int n, int k, int i, vector<vector<int>> &vv, vector<int> &curr){
        if(curr.size()==k){
            vv.push_back(curr);
            return;
        }
        for(; i<=n; ++i){
                curr.push_back(i);
                combinations(n,k,i+1,vv,curr);
                curr.pop_back();
        }
    }
};

还是12ms Ac,并不是最快的

上面的解法有点通用性,实际上并不是需要频繁的push_back或pop_back

class Solution {
public:
    vector<vector<int> > combine(int n, int k) {
        v.resize(k);
        dfs(1, n, k);
        return r;
    }
private:
    vector<vector<int> > r;
    vector<int> v;
    void dfs(int i, int n, int k) {
        while (i <= n) {
            v[v.size() - k] = i++;
            if (k > 1)
                dfs(i, n, k - 1);
            else
                r.push_back(v);
        }
    }
};

8ms AC

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值