您的位置:首页 > 其它

LeetCode:Combinations

2016-05-24 11:37 267 查看
Combinations

Total Accepted: 75841 Total
Submissions: 219221 Difficulty: Medium

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


Subscribe to see which companies asked this question

Hide Tags
 Backtracking

Hide Similar Problems
 (M) Combination Sum (M)
Permutations

思路:

例:n = 4, k = 3;有combs,comb数组

组合情况有:

1)1 2 3

2)1 2 4

3)1 3 4

4)2 3 4

生成过程:

comb=[], k=3,初始状态;

comb=[1], k=2,加入1;

comb=[1,2], k=1,加入2;

comb=[1,2,3], k=0;加入3,结果添加到combs;

comb=[1,2], k=1;去掉3

comb=[1,2,4], k=0;加入3,结果添加到combs;

comb=[1,2], k=1,去掉4;

comb=[1], k=2,这时由于已经遍历到4(==n),要再去掉2;

comb=[1,3], k=1,加入3;

comb=[1,3,4], k=0,加入4,结果添加到combs;

comb=[1,3], k=1,去掉4;

comb=[1], k=2,这时由于已经遍历到n(==4),要再去掉3;

comb=[1,4], k=1,加入4;已经到n;

comb=[1], k=2,去掉4;

comb=[], k=3,去掉1;

comb=[2], k=2,加入2;

comb=[2,3], k=1,加入3;

comb=[2,3,4], k=0,加入4,结果添加到combs;

c++ code:

class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> combs;
vector<int> comb;
combine(combs,comb,1,n,k);
return combs;
}
void combine(vector<vector<int>> &combs, vector<int> &comb,int begin,int n,int k) {

if(k==0){
combs.push_back(comb);
return;
}

for(int i=begin;i<=n;i++) {
comb.push_back(i);
combine(combs,comb,i+1,n,k-1);
comb.pop_back();
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: