combinations
1354 ワード
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:
ode:
[java] view plain copy
public class Solution {
public ArrayList> combine(int n, int k) {
ArrayList list = new ArrayList();
ArrayList> listsAll = new ArrayList>();
allCombine(n, k, 1, 0, list, listsAll);
return listsAll;
}
public void allCombine(int n, int k, int current, int length, ArrayList list, ArrayList> listsAll) {
if (current > n) return;
list.add(current);
length++;
if (list.size() == k) {
print(list,listsAll);
}
allCombine(n, k, current + 1, length, list, listsAll);
list.remove(list.size() - 1);
allCombine(n, k, current + 1, length, list, listsAll);
}
public void print(ArrayList list, ArrayList> listsAll) {
ArrayList temp = new ArrayList(list);
listsAll.add(temp);
}
}
For example, If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
C ode:
[java] view plain copy
public class Solution {
public ArrayList> combine(int n, int k) {
ArrayList list = new ArrayList();
ArrayList> listsAll = new ArrayList>();
allCombine(n, k, 1, 0, list, listsAll);
return listsAll;
}
public void allCombine(int n, int k, int current, int length, ArrayList list, ArrayList> listsAll) {
if (current > n) return;
list.add(current);
length++;
if (list.size() == k) {
print(list,listsAll);
}
allCombine(n, k, current + 1, length, list, listsAll);
list.remove(list.size() - 1);
allCombine(n, k, current + 1, length, list, listsAll);
}
public void print(ArrayList list, ArrayList> listsAll) {
ArrayList temp = new ArrayList(list);
listsAll.add(temp);
}
}