1. 程式人生 > 實用技巧 >面試題 08.04. 冪集

面試題 08.04. 冪集

題幹

冪集。編寫一種方法,返回某集合的所有子集。集合中不包含重複的元素。

說明:解集不能包含重複的子集。

示例:

輸入: nums = [1,2,3]
 輸出:
[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

來源:力扣(LeetCode)

連結:https://leetcode-cn.com/problems/power-set-lcci

思路

backtrack的模板

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); } } }