leetcode72:combinations

题目描述

给出两个整数n和k,返回从1到n中取k个数字的所有可能的组合
例如:
如果n=4,k=2,结果为
[↵  [2,4],↵  [3,4],↵  [2,3],↵  [1,2],↵  [1,3],↵  [1,4],↵]
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],↵]↵

示例1

输入

复制
2,1

输出

复制
[[1],[2]]
示例2

输入

复制
3,1

输出

复制
[[1],[2],[3]]

class Solution {
public:
    /**
     *
     * @param n int整型
     * @param k int整型
     * @return int整型vector<vector<>>
     */
    void DFS(vector <vector<int> >&ret,vector<int> &path,int n,int start,int rest){
        if (!rest)
            ret.push_back(path);
        else {
            for (int i=start;i<=n-rest+1;++i){
                path.push_back(i);
                DFS(ret,path,n,i+1,rest-1);
                path.pop_back();
            }
        }
    }
    vector<vector<int> > combine(int n, int k) {
        // write code here
        vector <vector<int>> ret;
        vector<int> path;
        DFS(ret,path,n,1,k);
        return ret;
        
    }
};



原文地址:https://www.cnblogs.com/hrnn/p/13415780.html