77.leetcode Combinations(medium)[回溯递归]

来源:互联网 发布:六盘水网络菜市场 编辑:程序博客网 时间:2024/05/16 05:00

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


class Solution {public:    void getCombine(int start,int step,int n,vector<int> &subsets,vector<vector<int> > &result,vector<int> &temp)    {        if(step == 0)        {            if(temp.size() != 0)            {                result.push_back(temp);            }            return;        }        for(int i=start;i<=n-step;i++)        {            temp.push_back(subsets[i]);            getCombine(i+1,step-1,n,subsets,result,temp);            temp.pop_back();        }        return ;    }    vector<vector<int>> combine(int n, int k) {         vector<int> subsets;         vector<vector<int> > result;         if(n<=0 || k<=0) return result;         for(int i=1;i<=n;i++)            subsets.push_back(i);         vector<int> temp;         getCombine(0,k,n,subsets,result,temp);         return result;    }};


0 0
原创粉丝点击