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 { public ArrayList<ArrayList<Integer>> combine(int n, int k) { ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>(); if(k>n) { return ret; } ArrayList<Integer> empty = new ArrayList<Integer>(); ret.add(empty); for(int i=1;i<=n;i++) { ArrayList<ArrayList<Integer>> tmp = new ArrayList<ArrayList<Integer>>(); for(ArrayList<Integer> lst : ret) { if(lst.size()<k) { ArrayList<Integer> lst2 = new ArrayList<Integer>(lst); lst2.add(i); tmp.add(lst2); } } ret.addAll(tmp); } for(int i=0;i<ret.size();i++) { if(ret.get(i).size()<k) { ret.remove(i); i--; } } return ret; } }
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
List<Integer> empty = new ArrayList<Integer>();
res.add(empty);
while(k>0) {
List<List<Integer>> newRes = new ArrayList<List<Integer>>();
for(int i=1;i<=n;i++) {
for(List<Integer> old:res) {
if(old.size()==0 || old.get(old.size()-1)<i) {
List<Integer> newLst = new ArrayList<Integer>(old);
newLst.add(i);
newRes.add(newLst);
}
}
}
res = newRes;
k--;
}
return res;
}
}
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (n < 1 || k < 0 || k > n) {
return ret;
}
List<Integer> empty = new ArrayList<Integer>();
ret.add(empty);
for (int i = 1; i <= n; i++) {
List<List<Integer>> tmpRet = new ArrayList<List<Integer>>();
for (List<Integer> list : ret) {
if (list.size() < k && list.size() + (n - i + 1) >= k) {
List<Integer> newList = new ArrayList<Integer>(list);
newList.add(i);
tmpRet.add(newList);
}
}
ret.addAll(tmpRet);
}
for (int i = 0; i < ret.size(); i++) {
if (ret.get(i).size() != k) {
ret.remove(i);
i--;
}
}
return ret;
}
}
=======
public class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
if (n < 1 || k <= 0) {
return res;
}
helper(n, k, 1, new ArrayList<Integer>(), res);
return res;
}
private void helper(int n, int k, int cur, List<Integer> list, List<List<Integer>> res) {
if (list.size() == k) {
List<Integer> newList = new ArrayList<Integer>(list);
res.add(newList);
} else {
for (int i = cur; i <= n; i++) {
list.add(i);
helper(n, k, i + 1, list, res);
list.remove(list.size() - 1);
}
}
}
}
没有评论:
发表评论