From : https://leetcode.com/problems/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:
void putRest(vector<vector<int>>& res, vector<int>& cur, int lastIndex, int needNum, int n) {
if(needNum == 0) {res.push_back(cur); return;}
for(int i=lastIndex+1; i<=n-needNum+1; i++) {
cur.push_back(i);
putRest(res, cur, i, needNum-1, n);
cur.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
if(k>n || k<=0) return res;
int last = n-k+1;
for(int i=1; i<=last; i++) {
vector<int> cur;
cur.push_back(i);
putRest(res, cur, i, k-1, n);
}
return res;
}
};
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
if (n >= k && k > 0) {
combine(1, k, n, new LinkedList<Integer>(), ans);
}
return ans;
}
private void combine(int I, int K, int N, LinkedList<Integer> cur,
List<List<Integer>> ans) {
if (K == 0) {
ans.add(new ArrayList<Integer>(cur));
return;
}
for (int i = I; i <= N - K + 1; ++i) {
cur.add(i);
combine(i + 1, K - 1, N, cur, ans);
cur.removeLast();
}
}
}
473

被折叠的 条评论
为什么被折叠?



