【LeetCode OJ】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],
]

java code : 注意后台数据没有 n == 0 || k == 0 以及 n < k 的这种情况,不是很严格。

import java.util.ArrayList;

public class HelloTest {

	public static void main(String[] args) 
	{
		HelloTest ht = new HelloTest();
		ArrayList<ArrayList<Integer>> res = ht.combine(4,2);
		System.out.println(res.toString());
		
	}
	public ArrayList<ArrayList<Integer>> combine(int n, int k) 
	{
		ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
		if(n == 0 || k == 0)
			return res;
		if(n <= k)
		{
			ArrayList<Integer> tmp = new ArrayList<Integer>(n);
			for(int i = 1; i <= n; i++)
				tmp.add(i);
			res.add(tmp);
			return res;
		}
		ArrayList<Integer> tmp = new ArrayList<Integer>();
		fun(res, tmp, n, k, 1);
		return res;
	}
	private void fun(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> tmp, int n, int k, int depth)
	{
		if(tmp.size() == k)
		{
			res.add(new ArrayList<Integer>(tmp));// notice: res.add(tmp) is wrong.
			return ;
		}
		for(int i = depth; i <= n; i++)
		{
			tmp.add(i);
			fun(res, tmp, n, k, i+1);
			tmp.remove(tmp.size() -1);
		}
	}

}


你可能感兴趣的:(java,LeetCode,ArrayList)