LeetCode 排列組合 題目匯總

46. Permutations

Given a collection of distinct numbers, return all possible permutations.

For example,
[1,2,3] have the following permutations:

[
  [1,2,3],
  [1,3,2],
  [2,1,3],
  [2,3,1],
  [3,1,2],
  [3,2,1]
]

思路

對于nums數(shù)組中的每一個數(shù)窑邦,都依次放入結(jié)果集中,如果結(jié)果集中已經(jīng)包含這個數(shù)壕探,就繼續(xù)下一次循環(huán)冈钦。

以數(shù)組[1,2,3]為例,每次循環(huán)的結(jié)果是:

[1,2,3]
[1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
[3,2,1]

代碼

public List<List<Integer>> permute(int[] nums) {
   List<List<Integer>> list = new ArrayList<>();
   backtrack(list, new ArrayList<>(), nums);
   return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums){
   if(tempList.size() == nums.length){
      list.add(new ArrayList<>(tempList));
   } else{
      for(int i = 0; i < nums.length; i++){ 
         if(tempList.contains(nums[i])) continue; // element already exists, skip
         tempList.add(nums[i]);
         backtrack(list, tempList, nums);
         tempList.remove(tempList.size() - 1);
      }
   }
} 

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

思路

這道題比上一道題多了一個條件浩蓉,即數(shù)組中有重復(fù)的數(shù)派继。有兩種思路:

  • 仍然按照上一道題的解法宾袜,但是把結(jié)果用set保存捻艳,最終轉(zhuǎn)換成list。
  • 考慮數(shù)組中有相同的數(shù)庆猫,規(guī)定必須按照從前到后的順序使用數(shù)字认轨,即數(shù)組[1,1],在組合時月培,必須先使用第一個1嘁字,才能再使用第二個1,這樣就避免了結(jié)果集重復(fù)的情況杉畜。

代碼

public List<List<Integer>> permuteUnique(int[] nums) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, new boolean[nums.length]);
    return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, boolean [] used){
    if(tempList.size() == nums.length){
        list.add(new ArrayList<>(tempList));
    } else{
        for(int i = 0; i < nums.length; i++){
            if(used[i] || i > 0 && nums[i] == nums[i-1] && !used[i - 1]) continue;
            used[i] = true; 
            tempList.add(nums[i]);
            backtrack(list, tempList, nums, used);
            used[i] = false; 
            tempList.remove(tempList.size() - 1);
        }
    }
}

78. Subsets

Given a set of distinct integers, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,3], a solution is:

[
  [3],
  [1],
  [2],
  [1,2,3],
  [1,3],
  [2,3],
  [1,2],
  []
]

思路

與題目Permutations類似纪蜒,但是Permutations是達(dá)到數(shù)組長度才將結(jié)果保存,而本題目是求子集此叠,任何集合都需要保存纯续。其中for循環(huán)的條件也稍微有些變化。

代碼

public List<List<Integer>> subsets(int[] nums) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, 0);
    return list;
}

private void backtrack(List<List<Integer>> list , List<Integer> tempList, int [] nums, int start){
    list.add(new ArrayList<>(tempList));
    for(int i = start; i < nums.length; i++){
        tempList.add(nums[i]);
        backtrack(list, tempList, nums, i + 1);
        tempList.remove(tempList.size() - 1);
    }
}

90. Subsets II

Given a collection of integers that might contain duplicates, nums, return all possible subsets.

Note: The solution set must not contain duplicate subsets.

For example,
If nums = [1,2,2], a solution is:

[
  [2],
  [1],
  [1,2,2],
  [2,2],
  [1,2],
  []
]

思路

處理重復(fù)的數(shù)灭袁,和上面是一個思路猬错,即只允許用前面的數(shù)字。

代碼

public List<List<Integer>> subsetsWithDup(int[] nums) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, 0);
    return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int start){
    list.add(new ArrayList<>(tempList));
    for(int i = start; i < nums.length; i++){
        if(i > start && nums[i] == nums[i-1]) continue; // skip duplicates
        tempList.add(nums[i]);
        backtrack(list, tempList, nums, i + 1);
        tempList.remove(tempList.size() - 1);
    }
} 

39. Combination Sum

Given a set of candidate numbers (C) (without duplicates) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:

[
  [7],
  [2, 2, 3]
]

思路

Subsets是同一個思路茸歧,只不過這次不是求子集倦炒,而是加上了限制條件:和為指定的值。

代碼

public List<List<Integer>> combinationSum(int[] nums, int target) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, target, 0);
    return list;
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
    if(remain < 0) return;
    else if(remain == 0) list.add(new ArrayList<>(tempList));
    else{ 
        for(int i = start; i < nums.length; i++){
            tempList.add(nums[i]);
            backtrack(list, tempList, nums, remain - nums[i], i); // not i + 1 because we can reuse same elements
            tempList.remove(tempList.size() - 1);
        }
    }
}

40. Combination Sum II (can't reuse same element)

Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

Each number in C may only be used once in the combination.

Note:
All numbers (including target) will be positive integers.
The solution set must not contain duplicate combinations.
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:

[
  [1, 7],
  [1, 2, 5],
  [2, 6],
  [1, 1, 6]
]

思路

和上一題有兩點(diǎn)不同的地方:

  • 數(shù)組中可能有重復(fù)的數(shù)字
  • 不能重復(fù)利用數(shù)組中的數(shù)字

解決數(shù)組中可能有重復(fù)的數(shù)字:

if(i > start && nums[i] == nums[i-1]) continue; // skip duplicates

解決不能重復(fù)利用數(shù)組中的數(shù)字(上一題中最后是i软瞎,而不是i + 1):

backtrack(list, tempList, nums, remain - nums[i], i + 1);

代碼

public List<List<Integer>> combinationSum2(int[] nums, int target) {
    List<List<Integer>> list = new ArrayList<>();
    Arrays.sort(nums);
    backtrack(list, new ArrayList<>(), nums, target, 0);
    return list;
    
}

private void backtrack(List<List<Integer>> list, List<Integer> tempList, int [] nums, int remain, int start){
    if(remain < 0) return;
    else if(remain == 0) list.add(new ArrayList<>(tempList));
    else{
        for(int i = start; i < nums.length; i++){
            if(i > start && nums[i] == nums[i-1]) continue; // skip duplicates
            tempList.add(nums[i]);
            backtrack(list, tempList, nums, remain - nums[i], i + 1);
            tempList.remove(tempList.size() - 1); 
        }
    }
} 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末逢唤,一起剝皮案震驚了整個濱河市拉讯,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌智玻,老刑警劉巖遂唧,帶你破解...
    沈念sama閱讀 218,546評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異吊奢,居然都是意外死亡盖彭,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評論 3 395
  • 文/潘曉璐 我一進(jìn)店門页滚,熙熙樓的掌柜王于貴愁眉苦臉地迎上來召边,“玉大人,你說我怎么就攤上這事裹驰∷砦酰” “怎么了?”我有些...
    開封第一講書人閱讀 164,911評論 0 354
  • 文/不壞的土叔 我叫張陵幻林,是天一觀的道長贞盯。 經(jīng)常有香客問我,道長沪饺,這世上最難降的妖魔是什么躏敢? 我笑而不...
    開封第一講書人閱讀 58,737評論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮整葡,結(jié)果婚禮上件余,老公的妹妹穿的比我還像新娘。我一直安慰自己遭居,他們只是感情好啼器,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著俱萍,像睡著了一般端壳。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上枪蘑,一...
    開封第一講書人閱讀 51,598評論 1 305
  • 那天损谦,我揣著相機(jī)與錄音,去河邊找鬼腥寇。 笑死成翩,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的赦役。 我是一名探鬼主播麻敌,決...
    沈念sama閱讀 40,338評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼掂摔!你這毒婦竟也來了术羔?” 一聲冷哼從身側(cè)響起赢赊,我...
    開封第一講書人閱讀 39,249評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎级历,沒想到半個月后释移,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,696評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡寥殖,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評論 3 336
  • 正文 我和宋清朗相戀三年玩讳,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片嚼贡。...
    茶點(diǎn)故事閱讀 40,013評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡熏纯,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出粤策,到底是詐尸還是另有隱情樟澜,我是刑警寧澤,帶...
    沈念sama閱讀 35,731評論 5 346
  • 正文 年R本政府宣布叮盘,位于F島的核電站秩贰,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏柔吼。R本人自食惡果不足惜毒费,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望嚷堡。 院中可真熱鬧蝗罗,春花似錦艇棕、人聲如沸蝌戒。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽北苟。三九已至,卻和暖如春打瘪,著一層夾襖步出監(jiān)牢的瞬間友鼻,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評論 1 270
  • 我被黑心中介騙來泰國打工闺骚, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留彩扔,地道東北人。 一個月前我還...
    沈念sama閱讀 48,203評論 3 370
  • 正文 我出身青樓僻爽,卻偏偏與公主長得像虫碉,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子胸梆,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評論 2 355

推薦閱讀更多精彩內(nèi)容

  • 背景 一年多以前我在知乎上答了有關(guān)LeetCode的問題, 分享了一些自己做題目的經(jīng)驗(yàn)敦捧。 張土汪:刷leetcod...
    土汪閱讀 12,745評論 0 33
  • 將模擬器選擇為Generic iOS Device
    純陽子_閱讀 1,071評論 0 1
  • 東山島南門灣兢卵,自古以來习瑰,享譽(yù)海內(nèi)外。這里海灣遼闊秽荤、沙灘平緩甜奄、綠樹成蔭,極具南國濱海風(fēng)光特色窃款,一直深受眾多游...
    程金銘閱讀 2,866評論 1 8
  • 有些事情贺嫂,也許要很多的時間才可以證明。有些事情雁乡,也許只需要你一個信任的眼神便已足夠第喳。如同我們初見時,陌生的你踱稍,陌生...
    邱斌閱讀 231評論 0 0