Combinations

Posted Will Wu的学习笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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],
]

 分析: 组合的实现,之前实现过全排列,递归求解

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        //爆搜
        vector<vector<int>> res;
        if (k==0 || n==0)
            return res;
       
        for(int base=1; base<=(n-k+1); base++){
            vector<int> tempres(1,base);
            helper(base,n,k-1,tempres,res);
        }
        return res;
    }
    void helper(int base,int n, int num, vector<int>& tempres, vector<vector<int>>& res){
        if(num==0){
            res.push_back(tempres);
            return;
        }
        if(base+num-1>n){
            return;
        }
        for(int i=base+1; i<=n; i++){
            tempres.push_back(i);
            helper(i,n,num-1,tempres,res);
            tempres.pop_back();
        }
    }
};

 

以上是关于Combinations的主要内容,如果未能解决你的问题,请参考以下文章

个人记录-LeetCode 77. Combinations

个人记录-LeetCode 77. Combinations

leetcode-Combinations-77

[Lintcode]152. Combinations/[Leetcode]77. Combinations

LeetCode(17)Letter Combinations of a Phone Number

leetcode17. Letter Combinations of a Phone Number