Combinations

来源:互联网 发布:2016网络零售交易额 编辑:程序博客网 时间:2024/06/07 09:13

题目描述:

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],]
解题思路:使用回溯法


AC代码如下:

class Solution {public:vector<vector<int>> combine(int n, int k) {vector<vector<int>> ans;if (n == 0 || k == 0) return ans;vector<int> select(k);int idx = 0;while (idx >= 0){select[idx]++;if (select[idx] > n){--idx;}else{if (idx == k - 1){ans.push_back(select);}else{idx++;select[idx] = select[idx - 1];}}}return ans;}};


0 0