leetcode 46 47全配列2 Java
1890 ワード
構想
46題は主に再帰的な方法で、左から右に配列を遍歴し、これによってこの下付き文字と後ろの数字を2つ交換し、再帰を続け、現在の下付き文字を1つの変数startで記録する.startが配列の下付き(nums.length()を越えるまで終了します.47題は主に46題より1つ多くの判断を繰り返す処理であり、47題のコードの中で46題より数行しか多くない.例えば2,2,1,1に対して、最初の要素2個と1個の2個が交換されることを確保し、1個の1個と交換される(それは自分で交換しても1回の交換であることに注意する)
(参考:https://blog.csdn.net/chenchaofuck1/article/details/51194976 https://blog.csdn.net/mebiuw/article/details/51184815 )
コードは次のとおりです.
46題
47題
46題は主に再帰的な方法で、左から右に配列を遍歴し、これによってこの下付き文字と後ろの数字を2つ交換し、再帰を続け、現在の下付き文字を1つの変数startで記録する.startが配列の下付き(nums.length()を越えるまで終了します.47題は主に46題より1つ多くの判断を繰り返す処理であり、47題のコードの中で46題より数行しか多くない.例えば2,2,1,1に対して、最初の要素2個と1個の2個が交換されることを確保し、1個の1個と交換される(それは自分で交換しても1回の交換であることに注意する)
(参考:https://blog.csdn.net/chenchaofuck1/article/details/51194976 https://blog.csdn.net/mebiuw/article/details/51184815 )
コードは次のとおりです.
46題
//46 98%
List> res = new ArrayList<>();
public List> permute(int[] nums) {
res.clear();
dfs(nums, 0);//
return res;
}
public void dfs(int[] n, int start) {//start
if( start >= n.length) {
List list = new ArrayList();
for(int i : n) {
list.add(i);
}
res.add(list);
return;
}
for(int i = start; i< n.length; i++) {//i start , start+1 ,
int temp= n[i];
n[i] = n[start];
n[start] = temp;
dfs(n, start + 1);//
//
n[start] = n[i];
n[i] = temp;
}
}
47題
//47 43%
List> res = new ArrayList<>();
public List> permuteUnique(int[] nums) {
res.clear();
dfs2(nums, 0);//
return res;
}
public void dfs2(int[] n, int start) {//start
if( start == n.length) {
List list = new ArrayList();
for(int i=0; i set = new HashSet();
for(int i = start; i< n.length; i++) {//i start , start+1 ,
if(set.contains(n[i])) {
continue;
}
set.add(n[i]);// ,
int temp= n[i];
n[i] = n[start];
n[start] = temp;
dfs2(n, start + 1);//
//
n[start] = n[i];
n[i] = temp;
}
}