77. Combinations - Medium
发布时间:2020-12-14 05:10:53 所属栏目:大数据 来源:网络整理
导读:Given two integers? n ?and? k ,return all possible combinations of? k numbers out of 1 ...? n . Example: Input:?n = 4,k = 2Output:[ [2,4],[3,[2,3],[1,2],] ? use DFS (backtracking) time = O(k * C(n,k)),space = O( C(n,k) ) class Solution { p
Given two integers?n?and?k,return all possible combinations of?knumbers out of 1 ...?n. Example: Input:?n = 4,k = 2 Output: [ [2,4],[3,[2,3],[1,2],] ? use DFS (backtracking) time = O(k * C(n,k)),space = O( C(n,k) ) class Solution { public List<List<Integer>> combine(int n,int k) { List<List<Integer>> res = new ArrayList<>(); dfs(n,k,1,new ArrayList<>(),res); return res; } public void dfs(int n,int k,int start,List<Integer> list,List<List<Integer>> res) { if(list.size() == k) { res.add(new ArrayList<>(list)); return; } for(int i = start; i <= n; i++) { list.add(i); dfs(n,i + 1,list,res); list.remove(list.size() - 1); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |