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],
]
public class Solution {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> result = new ArrayList<Integer>();
int n,k;
public List<List<Integer>> combine(int n, int k) {
this.n = n;
this.k = k;
backtracking(0);
return this.results;
}
public void backtracking(int index){
if(index == k){
List<Integer> copyOfResult = new ArrayList<Integer>();
copyOfResult.addAll(result);
results.add(copyOfResult);
}
else{
int i;
if(result.isEmpty()) i = 1;
else i = result.get(index-1) + 1;
for(;i <= n;i++){
result.add(i);
backtracking(index+1);
result.remove(index);
}
}
}
}
可是不幸超时了
看了大神的代码
http://blog.csdn.net/ljiabin/article/details/41787957
public class Solution {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> result = new ArrayList<Integer>();
int n,k;
public List<List<Integer>> combine(int n, int k) {
this.n = n;
this.k = k;
backtracking(0,1);
return this.results;
}
public void backtracking(int index,int from){
if(index == k){
List<Integer> copyOfResult = new ArrayList<Integer>(result);
//copyOfResult.addAll(result);
results.add(copyOfResult);
}
else{
for(int i = from;i <= n;i++){
result.add(i);
backtracking(index+1,i+1);
result.remove(index);
}
}
}
}