面試題 08.04. 冪集
阿新 • • 發佈:2021-01-08
輸入: nums = [1,2,3] 輸出: [ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
private void backtrack("原始引數") { //終止條件(遞迴必須要有終止條件) if ("終止條件") {//一些邏輯操作(可有可無,視情況而定) return; } for (int i = "for迴圈開始的引數"; i < "for迴圈結束的引數"; i++) { //一些邏輯操作(可有可無,視情況而定) //做出選擇 //遞迴 backtrack("新的引數"); //一些邏輯操作(可有可無,視情況而定) //撤銷選擇 } }
class Solution { public List<List<Integer>> subsets(int[] nums) { //結果集合 List<List<Integer>> list = new ArrayList(); //回溯方法 backtrack(list,new ArrayList<>(),nums,0); return list; } public void backtrack(List<List<Integer>>list,List<Integer>tempList,int []nums,int start){ list.add(new ArrayList<>(tempList)); for(int i = start;i<nums.length;i++) { tempList.add(nums[i]); backtrack(list, tempList, nums, i + 1); tempList.remove(tempList.size() - 1); } } }