例:1, 2, 3。a, b。
排列組合后,1 a,1 b,2 a,2 b,3 a,3 b。
怎么設定,1只和a組合。
結果為:1 a,2 a,2 b,3 a,3 b。
有明白的大神麻煩提供個思路或者能把代碼貼上來就太好了。萬分感謝。
uj5u.com熱心網友回復:
類似于這樣?public List<String> longestCommonPrefix(String[] strs1, String[] strs2, int a, int b) {
List<String> result = new LinkedList<>();
if (strs1.length==0 || strs2.length==0){
return result;
}
for (int i=0;i<strs1.length;i++){
if (i==a){
result.add(strs1[i]+strs2[b]);
}else{
for (int j=0;j<strs2.length;j++){
result.add(strs1[i]+strs2[j]);
}
}
}
return result;
}
uj5u.com熱心網友回復:
您好,請問有完全的代碼嗎?可以給我發一下嗎?
uj5u.com熱心網友回復:
class Solution {
//引數strs1陣列1,strs2陣列2,a陣列1中指定位置,b與陣列1中指定值組合的值在陣列2中的下標
public List<String> longestCommonPrefix(String[] strs1, String[] strs2, int a, int b) {
List<String> result = new LinkedList<>();
if (strs1.length==0 || strs2.length==0){//判斷有空陣列時直接回傳空集合
return result;
}
for (int i=0;i<strs1.length;i++){//回圈陣列1
if (i==a){//判斷陣列1中指定值僅與陣列2中指定值組合
result.add(strs1[i]+strs2[b]);
}else{//陣列1中其余值與陣列2中的值進行組合
for (int j=0;j<strs2.length;j++){
result.add(strs1[i]+strs2[j]);
}
}
}
return result;
}
public static void main(String[] args) {
Solution solution=new Solution();
String[] aaa=new String[]{"1","2","3","4"};//陣列1
String[] bbb=new String[]{"a","b","c","d"};//陣列2
List str = solution.longestCommonPrefix(aaa,bbb,0,0);
System.out.println(str);
}
}
uj5u.com熱心網友回復:
其實你還可以寫更優的代碼,直接把1拿出來,其它的元素放到兩個set,然后笛卡爾積轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/224556.html
標籤:Java相關
上一篇:有關1.7Hashmap問題
