Created
July 21, 2015 18:36
-
-
Save fever324/822a84efd0be0cc54bc2 to your computer and use it in GitHub Desktop.
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], ]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class Solution { | |
| public List<List<Integer>> combine(int n, int k) { | |
| List<List<Integer>> solution = new ArrayList<>(); | |
| dfs(n, k, 1, solution, new ArrayList<Integer>()); | |
| return solution; | |
| } | |
| private void dfs(int n, int k, int start, List<List<Integer>> l, List<Integer> path) { | |
| if(k == 0) { | |
| l.add(path); | |
| return; | |
| } | |
| for(int i = start ; i <= n; i++) { | |
| List<Integer> nPath = new ArrayList<>(path); | |
| nPath.add(i); | |
| dfs(n, k - 1, i + 1, l ,nPath); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment