LeetCode77: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],
]
Hide Tags Backtracking

给定一个数n。求1到n之间的全部的k个数的组合。
这个题目能够在纸上画下草图,明显能够用递归求解。递归的终止条件是k=0,而且因为须要将组合保存到集合vector中,还须要使用回溯法来保存数据。
runtime:8ms

class Solution {
public:
    vector<vector<int>> combine(int n, int k) {
        vector<vector<int>> result;
        vector<int> vec;
        helper(1,n,k,vec,result);
        return result;
    }

    void helper(int first,int last,int k,vector<int> & vec,vector<vector<int>> & result)
    {
        if(k==0)
        {
            result.push_back(vec);
            return ;
        }

        for(int i=first;i<=last-k+1;i++)
        {
            vec.push_back(i);
            helper(i+1,last,k-1,vec,result);
            vec.pop_back();
        }
    }

};
原文地址:https://www.cnblogs.com/yxwkf/p/5152100.html