leetcode 77. Combinations(java)
阿新 • • 發佈:2018-11-09
題目描述:
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
Example:
Input: n = 4, k = 2 Output: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
程式碼:
class Solution { public static List<List<Integer>> combine(int n, int k) { List<List<Integer>> res=new ArrayList<List<Integer>>(); if(n<k||k==0) return res; res=combine(n-1,k-1); if(res.isEmpty())//n==k時才有可能為空 res.add(new ArrayList<Integer>()); for(List<Integer> list:res){ list.add(n); } res.addAll(combine(n-1,k)); return res; } }
分析: