标签:++ for public nbsp ber ons dfs style new
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<>(); if(n == 0) return res; int[] nums = new int[n]; for(int i = 1; i <= n ; i++){ nums[i-1] = i; } List<Integer> mem = new ArrayList<>(); dfs(res, mem, nums, k , 0); return res; } public void dfs(List<List<Integer>> res, List<Integer> mem, int[] nums, int k, int deep){ if(mem.size() == k){ res.add(new ArrayList<>(mem)); return; } for(int i = deep; i < nums.length ; i++){ mem.add(nums[i]); dfs(res, mem, nums, k , i+1); mem.remove(mem.size()-1); } } }
标签:++ for public nbsp ber ons dfs style new
原文地址:http://www.cnblogs.com/joannacode/p/6108056.html