LeetCode:Combinations

Combinations



Total Accepted: 75841  Total Submissions: 219221  Difficulty: Medium

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

Subscribe to see which companies asked this question

Hide Tags
  Backtracking
Hide Similar Problems
  (M) Combination Sum (M) Permutations
























思路:

例:n = 4, k = 3;有combs,comb数组

组合情况有:

1)1 2 3

2)1 2 4

3)1 3 4

4)2 3 4

生成过程:

comb=[], k=3,初始状态;

comb=[1], k=2,加入1;

comb=[1,2], k=1,加入2;

comb=[1,2,3], k=0;加入3,结果添加到combs;

comb=[1,2], k=1;去掉3

comb=[1,2,4], k=0;加入3,结果添加到combs;

comb=[1,2], k=1,去掉4;

comb=[1], k=2,这时由于已经遍历到4(==n),要再去掉2;

comb=[1,3], k=1,加入3;

comb=[1,3,4], k=0,加入4,结果添加到combs;

comb=[1,3], k=1,去掉4;

comb=[1], k=2,这时由于已经遍历到n(==4),要再去掉3;

comb=[1,4], k=1,加入4;已经到n;

comb=[1], k=2,去掉4;

comb=[], k=3,去掉1;

comb=[2], k=2,加入2;

comb=[2,3], k=1,加入3;

comb=[2,3,4], k=0,加入4,结果添加到combs;






c++ code:

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> combs;
        vector<int> comb;
        combine(combs,comb,1,n,k);
        return combs;
    }
    void combine(vector<vector<int>> &combs, vector<int> &comb,int begin,int n,int k) {
        
        if(k==0){
            combs.push_back(comb);
            return;
        }
        
        for(int i=begin;i<=n;i++) {
            comb.push_back(i);
            combine(combs,comb,i+1,n,k-1);
            comb.pop_back();
        }
    }
};


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值