mybloger

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

55、子集

给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。

解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。

示例 1:

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

示例 2:

输入:nums = [0]
输出:[[],[0]]
class Solution {

   List<Integer> t = new ArrayList<Integer>();
   List<List<Integer>> ans = new ArrayList<List<Integer>>();

   public List<List<Integer>> subsets(int[] nums) {
       dfs(0,nums);
       return ans;
   }

   public void dfs(int cur,int[] nums) {
       if (cur == nums.length) {
           ans.add(new ArrayList<Integer>(t));
           return;
       }
       t.add(nums[cur]);
       dfs(cur + 1,nums);
       t.remove(t.size() - 1);

       dfs(cur + 1,nums);
   }
}

56、电话号码的字母组合

给定一个仅包含数字 2-9 的字符串,返回所有它能表示的字母组合。答案可以按 任意顺序 返回。

给出数字到字母的映射如下(与电话按键相同)。注意 1 不对应任何字母。

class Solution {
    public List<String> letterCombinations(String digits) {
        List<String> combinations = new ArrayList<String>();
        if (digits.length() == 0) {
            return combinations;
        }

        Map<Character,String> phoneMap = new HashMap<Character,String>(){{
            put('2', "abc");
            put('3', "def");
            put('4', "ghi");
            put('5', "jkl");
            put('6', "mno");
            put('7', "pqrs");
            put('8', "tuv");
            put('9', "wxyz");
        }};
        backtrack(combinations,phoneMap,digits,0,new StringBuffer());
        return combinations;
    }

    public void backtrack(List<String> combinations,Map<Character,String> phoneMap,
        String digits,int index,StringBuffer combination) {
            if (index == digits.length()) {
                combinations.add(combination.toString());
            }else {
                char digit = digits.charAt(index);
                String letters = phoneMap.get(digit);
                int lettersCount = letters.length();
                for (int i = 0;i < lettersCount;i++) {
                    combination.append(letters.charAt(i));
                    backtrack(combinations,phoneMap,digits,index + 1,combination);
                    combination.deleteCharAt(index);
                }
            }
        }
}
posted on 2025-07-10 21:47  万能包哥  阅读(7)  评论(0)    收藏  举报