`
hcx2013
  • 浏览: 88952 次
社区版块
存档分类
最新评论

Combinations

 
阅读更多

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 {
    public List<List<Integer>> combine(int n, int k) {
    	List<List<Integer>> res = new ArrayList<List<Integer>>();
    	if (n <= 0||n < k) {
    		return res;
    	}
    	ArrayList<Integer> list = new ArrayList<Integer>();
    	dfs(n,k,1,list, res);
    	return res;
    }

	private void dfs(int n, int k, int start, ArrayList<Integer> list,
			List<List<Integer>> res) {
		if (list.size() == k) {
			res.add(new ArrayList<Integer>(list));
			return;
		}
		for (int i = start; i <= n; i++) {
			list.add(i);
			dfs(n,k,i+1,list, res);
			list.remove(list.size()-1);
		}
	}
}
 
0
7
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics