题意以及限制条件
-
题目:
-
限制条件:
想到的所有可能解法
-
Ways_1——回溯
- 时间复杂度——O(n);空间复杂度——O(n)。
对应的代码
- Ways_1
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
backtrack(list, new ArrayList<Integer>(), n, k, 1);
return list;
}
private static void backtrack(List<List<Integer>> list, List<Integer> templist, int n, int remain, int start) {
//Terminator
if (remain == 0) {
list.add(new ArrayList<Integer>(templist));
} else {
//Current Logic
for (int i = start; i <= n - remain + 1; ++i) {
templist.add(i);
//Drill Down
backtrack(list, templist, n, remain - 1, i + 1);
//Restore Current Data
templist.remove(templist.size() - 1);
}
}
}
}