1. 程式人生 > 其它 >Mac檢視本機IP地址

Mac檢視本機IP地址

☆☆☆☆思路:回溯 + 剪枝。 如果使用Set去重,不能AC

class Solution {
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums); // 排序
        dfs(nums, 0, new ArrayList<>(), res);
        return res;
    }
    
// 舉例:[1,2,2] // 去重前:[ [],[1],[1,2],[1,2,2],[1,2],[2],[2,2],[2] ] // 去重後:[ [],[1],[1,2],[1,2,2],[2],[2,2] ] private void dfs(int[] nums, int start, List<Integer> list, List<List<Integer>> res) { res.add(new ArrayList<>(list)); for (int i = start; i < nums.length; i++) {
// 和上個數字相等就跳過, 注意是 i > start, 而不是大於0 // 在一個for迴圈中,所有被遍歷到的數都是屬於一個層級的。我們要讓一個層級中,必須出現且只出現一個2 // i > start 可以讓同一層級,不出現相同的元素;但允許不同層級之間的重複 // eg. 如果把所有當前與之前一個元素相同的都砍掉,那麼第二個2出現的時候,已經和前一個2相同了。 if (i > start && nums[i] == nums[i-1]) continue; list.add(nums[i]); dfs(nums, i
+ 1, list, res); list.remove(list.size() - 1); } } }