Skip to content

Commit 7b2f148

Browse files
committed
Update solution 047
1 parent 7384951 commit 7b2f148

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

README.md

-1
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@
99

1010
<h2 align="center">LeetCode Solution</h2>
1111

12-
## Introduction
1312
Complete solutions to Leetcode problems, updated daily.
1413

1514
## Solution List

solution/047.Permutations II/README.md

+57
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@
1919

2020
注意:第 i 个数字与第 j 个数字交换时,要求[i, j) 中没有与第 j 个数字相等的数。
2121

22+
解法①:
23+
2224
```java
2325
class Solution {
2426
public List<List<Integer>> permuteUnique(int[] nums) {
@@ -66,4 +68,59 @@ class Solution {
6668
nums[j] = t;
6769
}
6870
}
71+
```
72+
73+
解法②:
74+
75+
```java
76+
class Solution {
77+
public List<List<Integer>> permuteUnique(int[] nums) {
78+
List<List<Integer>> list = new ArrayList<>();
79+
permute(list, nums, 0);
80+
return list;
81+
}
82+
83+
private void permute(List<List<Integer>> list, int[] nums, int start) {
84+
int end = nums.length - 1;
85+
if (start == end) {
86+
List<Integer> tmp = new ArrayList<>();
87+
for (int val : nums) {
88+
tmp.add(val);
89+
}
90+
91+
list.add(tmp);
92+
93+
}
94+
95+
96+
int max = Integer.MIN_VALUE;
97+
int min = Integer.MAX_VALUE;
98+
for (int i = 0; i <= end; ++i) {
99+
max = Math.max(max, nums[i]);
100+
min = Math.min(min, nums[i]);
101+
}
102+
// 空间换取时间
103+
boolean[] flag = new boolean[max - min + 1];
104+
105+
for (int i = start; i <= end; ++i) {
106+
int index = nums[i] - min;
107+
if (!flag[index]) {
108+
// 说明当前的数没在之前出现过
109+
swap(nums, i, start);
110+
permute(list, nums, start + 1);
111+
swap(nums, i, start);
112+
113+
// 标志位设为 true
114+
flag[index] = true;
115+
}
116+
}
117+
118+
}
119+
120+
private void swap(int[] nums, int i, int j) {
121+
int t = nums[i];
122+
nums[i] = nums[j];
123+
nums[j] = t;
124+
}
125+
}
69126
```

0 commit comments

Comments
 (0)