29
07/2015
[LeetCode] Combinations
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], ]
解题思路:
这道题的题意是找到1-n的数字中找出k个数的所有组合。可以采用递归回溯法。比较简单。
class Solution { public: vector<vector<int>> combine(int n, int k) { vector<vector<int>> result; if(n < 0 || k < 0 || n < k){ return result; } vector<int> item; combineHelper(n, k, item, result); return result; } void combineHelper(int n, int k, vector<int> item, vector<vector<int>>& result){ int size = item.size(); if(size>=k){ result.push_back(item); return; } int last = size==0 ? 0 : item[size - 1]; if(n - last + size < k){ //无法达到k的大小了 return; } for(int i = last + 1; i <= n; i++){ item.push_back(i); combineHelper(n, k, item, result); item.pop_back(); } } };
转载请注明:康瑞部落 » [LeetCode] Combinations
0 条评论