[LeetCode] Combinations

简介:

要求

给定两个整数(n,k),返回长度为k,从1到n的所有组合(注意1.组合没有顺序  2. [2,3]和[3,2]为同一组,取前者小于后者的那一组)。

例如(4,2),结果为:

复制代码
[
  [2,4],
  [3,4],
  [2,3],
  [1,2],
  [1,3],
  [1,4],
]
复制代码

 

思路

递归


参考代码

复制代码
#include <iostream>
#include <vector>
using namespace std;

vector< vector<int> > ret;
vector<int> a;

void build(int dep, int maxDep, int n, int start)
{
    if (dep == maxDep)
    {
        ret.push_back(a);
        return;
    }

    for (int i = start; i <= n; ++i)
    {
        a[dep] = i;
        build(dep + 1, maxDep, n, i + 1);
    }
}

vector< vector<int> > combine(int n, int k)
{
    a.resize(k);
    ret.clear();
    build(0, k, n, 1);
    return ret;
}

int main()
{
    vector< vector<int> > vec = combine(4, 2);
    for (int i = 0; i < vec.size(); ++i)
    {
        for (int j = 0; j < vec[0].size(); ++j)
        {
            cout << vec[i][j] << " ";
        }
        cout << endl;
    }
}
复制代码

 






本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3706360.html,如需转载请自行联系原作者

相关文章
[LeetCode]--17. Letter Combinations of a Phone Number
Given a digit string, return all possible letter combinations that the number could represent. A mapping of digit to letters (just like on the telephone buttons) is given below. Input:D
1324 0
LeetCode - 17. Letter Combinations of a Phone Number
17. Letter Combinations of a Phone Number Problem's Link  ---------------------------------------------------------------------------- Mean:  给你一个数字串,输出其在手机九宫格键盘上的所有可能组合.
939 0
[LeetCode] Combinations
A typical backtracking problem. For any backtracking problem, you need to be think about three ascepts: What is a partial solution and when is it fi...
841 0
[LeetCode] Letter Combinations of a Phone Number
Well, a typical backtracking problem. Make sure you are clear with the following three problems: What is a partial solution and when is it finished?...
927 0