leetcode常考題目 subset i 和subset ii
阿新 • • 發佈:2019-01-01
Given two strings, write a method to decide if one is a permutation of the other.
java
public class Solution { public boolean Permutation(String A, String B) { if (A == null && B == null) { return true; } if (A == null || B == null) { return false; } if (A.length() != B.length()) { return false; } int[] arr = new int[256]; for (int i = 0; i < A.length(); i++) { arr[A.charAt(i)]++; } for (int i = 0; i < B.length(); i++) { if (--arr[B.charAt(i)] < 0) { return false; } } return true; } }
public class Solution { public List<List<Integer>> subsetsWithDup(int[] nums) { List<List<Integer>> result = new ArrayList<>(); if (nums == null || nums.length == 0) { result.add(new ArrayList<Integer>()); return result; } List<Integer> path = new ArrayList<>(); Arrays.sort(nums); dfs(nums, 0, path, result); return result; } private void dfs(int[] nums, int start, List<Integer> path, List<List<Integer>> result) { result.add(new ArrayList<Integer>(path)); if (start >= nums.length) { return; } for (int i = start; i < nums.length; i++) { if (i != start && nums[i] == nums[i - 1]) { continue; } else { path.add(nums[i]); dfs(nums, i + 1, path, result); path.remove(path.size() - 1); } } } }
follow up
Given a list of numbers that may has duplicate numbers, return all possible subsets
有重複元素
java