Combinations 全排列问题

来源:互联网 发布:sql注入防止php 编辑:程序博客网 时间:2024/05/24 13:28

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],]
class Solution {public:    vector<vector<int> > combine(int n, int k) {                vector< vector<int> > res;        vector<int>  path;        solve(1,0,k,n,path,res);        return res;    }        void solve(int index,int sum,int k,int n,vector<int> &path,vector< vector<int>> &res )    {        if(sum==k)        {            res.push_back(path);            return ;        }        for(int i=index;i<=n;i++)        {            path.push_back(i);            sum++;            solve(i+1,sum,k,n,path,res);            sum--;            path.pop_back();        }    }};
0 0