Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example
For example,
If n = 4 and k = 2, a solution is:
[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4]]
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>> result = new ArrayList<ArrayList<Integer>>(); ArrayList<Integer> tem = new ArrayList<Integer>(); if (n == 0 || k > n){ return result; } dfs(result, tem, n, k, 1); return result; } public void dfs(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> tem, int n, int k, int pos){ if (tem.size() == k){ result.add(new ArrayList<Integer>(tem)); return; } for(int i = pos; i <= n; i++){ tem.add(i); dfs(result, tem, n, k, i+1); tem.remove(tem.size() - 1); } } }
没有评论:
发表评论