public static void backTrack(int k, int start, int[] nums, List<Integer> tmp, List<List<Integer>> res) {
if (k == 0) return;
for (int i=start; i<=nums.length-k; i++) {
tmp.add(nums[i]);
backTrack(k-1, i+1, nums, tmp, res);
// using res.add(new ArrayList<>(tmp)) instead of res.add(tmp)
if (tmp.size() == 3) res.add(new ArrayList<>(tmp));
// reaches end remove the last added element
tmp.remove(tmp.size()-1);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
List<List<Integer>> res = new ArrayList<>();
int[] nums = new int[] {1, 2, 3, 4, 5};
backTrack(3, 0, nums, new ArrayList<>(), res);
System.out.println(res);
}
Notes. Combination -- Batacktrack
最新推荐文章于 2022-05-09 12:06:43 发布