1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| class Solution { public List<List<Integer>> combine(int n, int k) { int[] nums = new int[n]; for(int i = 1;i <= n;i++){ nums[i -1] = i; }
List<List<Integer>> ans = new ArrayList<>(); List<Integer> list = new ArrayList<>(); backtricking(nums,k,ans,list,0); return ans; } public void backtricking(int[] nums,int k,List<List<Integer>> ans, List<Integer> list,int input){ if(list.size() == k){ ans.add(new ArrayList<>(list)); return; }
for(int i = input; i < nums.length; i++){ list.add(nums[i]); backtricking(nums,k,ans,list,i + 1); list.remove(list.size() - 1); }
} }
|