Leetcode 77. Combinations

来源:互联网 发布:一建试题软件 编辑:程序博客网 时间:2024/05/18 09:05

Leetcode 77. Combinations

source url

题目描述

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

输入:最大数字n,组合所需元素数k
输出:k个元素的排列组合

思路

利用DFS,并保存DFS的路径,在递归层满足k时,结束;否则,继续以n个节点的方式展开。由于此处是排列组合,并且不可重复,故此处根据递增的方式展开,同时进行剪支。算法复杂度O(n2),约n(n+1)/2次。

代码

class Solution {public:    vector<vector<int>> ret;    int dim;    void backtrack(vector<int> b, int now, int n, int t){        //meet the require dimension        if(dim==t){            //insert current            b.push_back(now);            ret.push_back(b);//insert trace        }else{            b.push_back(now);            //next dimension should larger than this            for(int i = now+1;i<=n;i++){                backtrack(b,i,n,t+1);            }        }    }    vector<vector<int>> combine(int n, int k) {        vector<int> b;        dim = k;        for(int i=1;i<=n;i++){            backtrack(b,i,n,1);        }        return ret;    }};