点击量:482
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],
]
这题没有什么特别的思路吧,递归遍历。代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> result =new ArrayList<List<Integer>>(); func(1, new ArrayList(), result, n, k); return result; } /** * 递归计算K个n长度的for循环 */ public void func(int x, List<Integer> list, List<List<Integer>> result, int n, int k){ if(list.size() == k){ result.add(list); return; } for(int a=x;a<=n;a++){ list.add(a); func(a+1, new ArrayList(list), result, n, k); list.remove(list.size() -1); } return; } } |