1. 程式人生 > >(效率低下)77. Combinations C++回溯法

(效率低下)77. Combinations C++回溯法

沿用78題的思路

class Solution {
public:
    void backTrack(vector<int> ans, vector<int> nums, vector<vector<int>>& res, int times,int k)
    {
        if(ans.size() == k)
        {
            res.push_back(ans);
        }
        else
        {
            for(int i = times; i<nums.size(); i++)
            {
                ans.push_back(nums[i]);
                backTrack(ans,nums,res,i
+1,k); ans.pop_back(); } } } vector<vector<int>> combine(int n, int k) { vector<vector<int>> res; vector<int> ans; vector<int> nums; for(int i=1;i<=n;i++) nums.push_back(i);
int bgi = 0; backTrack(ans,nums,res,bgi,k); return res; } };