【LeetCode】77.Combinations(Medium)解题报告
题目地址:https://leetcode.com/problems/combinations/description/
题目描述:
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个数。
Solutions:
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
helper(res,new ArrayList<>(),0,n,k);
return res;
}
public void helper(List<List<Integer>> res,List<Integer> temp,int index , int n,int k){
if(temp.size()==k){
res.add(new ArrayList<>(temp));
return;
}
for(int i=index;i<n;i++){
temp.add(i+1);
helper(res,temp,i+1,n,k);
temp.remove(temp.size()-1);
}
}
}
Date:2018年1月3日