Subsets, Combination 与 Permutation
Combination 类问题最重要的是去重, dfs() 函数里带一个 index 参数可以很好的解决这个问题。
顺序问题中有“单序列”和“全序列”顺序,分别对应一个序列中元素的顺序和整个序列中子序列顺序。可以通过子序列翻转或者全局翻转操作,利用两次翻转相互抵消的特点解决序列顺序问题。
用数学语言描述就是: ' 代表 inverse
S = ABCD
S' = D'C'B'A'
(A'B'C'D')' = DCBA
public class Solution {
/**
* @param n: Given the range of numbers
* @param k: Given the numbers of combinations
* @return: All the combinations of k numbers out of 1..n
*/
public List<List<Integer>> combine(int n, int k) {
// write your code here
List<List<Integer>> rst = new ArrayList<List<Integer>>();
dfs(rst, new ArrayList<Integer>(), n, k, 0);
return rst;
}
private void dfs(List<List<Integer>> rst, List<Integer> list, int n, int k, int prev){
if(list.size() == k) {
rst.add(new ArrayList<Integer>(list));
//list.remove(list.size() - 1);
}
for(int i = prev + 1; i <= n; i++){
if(list.contains(i)) continue;
list.add(i);
dfs(rst, list, n, k, i);
list.remove(list.size() - 1);
}
}
}Last updated