LeetCode關(guān)于子集合 SubSet昭雌,排列 Permutation 和組合 Combination 的問(wèn)題

關(guān)于我的 Leetcode 題目解答,代碼前往 Github:https://github.com/chenxiangcyr/leetcode-answers


LeetCode題目:78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

候選數(shù)字無(wú)重復(fù)。

For example,

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

class Solution {
    public List<List<Integer>> subsets = new ArrayList<List<Integer>>();
    public List<Integer> subset = new ArrayList<Integer>();
    
    public List<List<Integer>> subsets(int[] nums) {
        travel(nums, 0);
        
        subsets.add(new ArrayList<Integer>());
        
        return subsets;
    }
    
    public void travel(int[] nums, int startIdx) {
        for(int i = startIdx; i < nums.length; i++) {
            subset.add(nums[i]);

            subsets.add(new ArrayList(subset));
            
            if(i + 1 < nums.length) {
                travel(nums, i + 1);
            }

            // backtracking
            subset.remove(subset.size() - 1);
        }
    }
}

LeetCode題目:90. Subsets II
Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

候選數(shù)字有重復(fù)叙量。

For example,

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

class Solution {
    public List<List<Integer>> subsets = new ArrayList<List<Integer>>();
    public List<Integer> subset = new ArrayList<Integer>();
    
    public List<List<Integer>> subsetsWithDup(int[] nums) {
        // 排序
        Arrays.sort(nums);
        
        travel(nums, 0);
        
        subsets.add(new ArrayList<Integer>());
        
        return subsets;
    }
    
    public void travel(int[] nums, int startIdx) {
        for(int i = startIdx; i < nums.length; i++) {
            subset.add(nums[i]);

            subsets.add(new ArrayList(subset));
            
            if(i + 1 < nums.length) {
                travel(nums, i + 1);
            }

            // backtracking
            subset.remove(subset.size() - 1);
            
            // 避免重復(fù)元素出現(xiàn)
            while(i + 1 < nums.length && nums[i + 1] == nums[i]) {
                i++;
            }
        }
    }
}

LeetCode題目:77. Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,

If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

class Solution {
    private List<List<Integer>> result = new ArrayList<List<Integer>>();
    
    private List<Integer> path = new ArrayList<Integer>();
    
    public List<List<Integer>> combine(int n, int k) {
        travel(n, k, 1);
        
        return result;
    }
    
    public void travel(int n, int k, int start) {
        if(start > n) {
            return;
        }
        
        for(int i = start; i <= n; i++) {
            path.add(i);

            if(path.size() == k) {
                result.add(new ArrayList<>(path));
            }
            else {
                // 遞歸,從下一個(gè)元素開始
                travel(n, k, i + 1);
            }

            // backtracking
            path.remove(path.size() - 1);
        }
    }
}

LeetCode題目: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.

候選數(shù)字無(wú)重復(fù)九串,但是每個(gè)數(shù)字可以出現(xiàn)多次绞佩。

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]
]

class Solution {
    private List<List<Integer>> result = new ArrayList<List<Integer>>();
    
    private List<Integer> path = new ArrayList<Integer>();
    
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        
        travel(candidates, target, 0);
        
        return result;
    }
    
    public void travel(int[] candidates, int target, int startIdx) {
        if(target < 0) {
            return;
        }
        
        else if(target == 0) {
            result.add(new ArrayList<>(path));
        }
        
        else {
            for(int i = startIdx; i < candidates.length; i++) {
                path.add(candidates[i]);
                
                // 遞歸,依舊從i開始猪钮,因?yàn)樵乜梢灾貜?fù)出現(xiàn)多次
                travel(candidates, target - candidates[i], i);
                
                // backtracking
                path.remove(path.size() - 1);
            }
        }
    }
}

LeetCode題目:40. Combination Sum II
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.

候選數(shù)字有重復(fù)品山,但是每個(gè)數(shù)字只能出現(xiàn)一次。

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]
]

class Solution {
    private List<List<Integer>> result = new ArrayList<List<Integer>>();
    
    private List<Integer> path = new ArrayList<Integer>();
    
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        Arrays.sort(candidates);
        
        travel(candidates, target, 0);
        
        return result;
    }
    
    public void travel(int[] candidates, int target, int startIdx) {
        if(target < 0) {
            return;
        }
        
        else if(target == 0) {
            result.add(new ArrayList<>(path));
        }
        
        else {
            for(int i = startIdx; i < candidates.length; i++) {
                // 跳過(guò)重復(fù)的元素
                if(i > startIdx && candidates[i] == candidates[i-1]) {
                    continue;
                }
                
                path.add(candidates[i]);
                
                // 遞歸烤低,從i + 1開始肘交,因?yàn)樵刂荒艹霈F(xiàn)一次
                travel(candidates, target - candidates[i], i + 1);
                
                // backtracking
                path.remove(path.size() - 1);
            }
        }
    }
}

LeetCode題目:46. Permutations
Given a collection of distinct numbers, return all possible permutations.

候選數(shù)字無(wú)重復(fù)。

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]
]

class Solution {
    public List<List<Integer>> permutations = new ArrayList<List<Integer>>();
    public List<Integer> permutation = new ArrayList<Integer>();
    
    public List<List<Integer>> permute(int[] nums) {
        travel(nums);
        
        return permutations;
    }
    
    public void travel(int[] nums) {
        for(int i = 0; i < nums.length; i++) {
            if(!permutation.contains(nums[i])) {
                permutation.add(nums[i]);
                
                // arrive the last digit
                if(permutation.size() == nums.length) {
                    permutations.add(new ArrayList(permutation));
                } else {
                    travel(nums);
                }
                
                // backtracking
                permutation.remove(permutation.size() - 1);
            }
        }
    
    }
}

LeetCode題目:47. Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.

候選數(shù)字有重復(fù)扑馁。

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

class Solution {
    public List<List<Integer>> permutations = new ArrayList<List<Integer>>();
    public List<Integer> permutation = new ArrayList<Integer>();
    
    public List<List<Integer>> permuteUnique(int[] nums) {
        Arrays.sort(nums);
        
        travel(nums, new boolean[nums.length]);
        
        return permutations;
    }
    
    public void travel(int[] nums, boolean [] visited) {
        for(int i = 0; i < nums.length; i++) {
            
            // 跳過(guò)重復(fù)的元素
            if(visited[i] || (i > 0 && nums[i] == nums[i-1] && !visited[i - 1])) {
                continue;
            }
            
            visited[i] = true;
            permutation.add(nums[i]);

            // arrive the last digit
            if(permutation.size() == nums.length) {
                permutations.add(new ArrayList(permutation));
            } else {
                travel(nums, visited);
            }

            // backtracking
            visited[i] = false;
            permutation.remove(permutation.size() - 1);
        }
    
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末涯呻,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子檐蚜,更是在濱河造成了極大的恐慌魄懂,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,546評(píng)論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件闯第,死亡現(xiàn)場(chǎng)離奇詭異市栗,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)咳短,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,224評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門填帽,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人咙好,你說(shuō)我怎么就攤上這事篡腌。” “怎么了勾效?”我有些...
    開封第一講書人閱讀 164,911評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵嘹悼,是天一觀的道長(zhǎng)叛甫。 經(jīng)常有香客問(wèn)我,道長(zhǎng)杨伙,這世上最難降的妖魔是什么其监? 我笑而不...
    開封第一講書人閱讀 58,737評(píng)論 1 294
  • 正文 為了忘掉前任,我火速辦了婚禮限匣,結(jié)果婚禮上抖苦,老公的妹妹穿的比我還像新娘。我一直安慰自己米死,他們只是感情好锌历,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,753評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著峦筒,像睡著了一般究西。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上勘天,一...
    開封第一講書人閱讀 51,598評(píng)論 1 305
  • 那天怔揩,我揣著相機(jī)與錄音,去河邊找鬼脯丝。 笑死商膊,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的宠进。 我是一名探鬼主播晕拆,決...
    沈念sama閱讀 40,338評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼材蹬!你這毒婦竟也來(lái)了实幕?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,249評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤堤器,失蹤者是張志新(化名)和其女友劉穎昆庇,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體闸溃,經(jīng)...
    沈念sama閱讀 45,696評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡整吆,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,888評(píng)論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了辉川。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片表蝙。...
    茶點(diǎn)故事閱讀 40,013評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖乓旗,靈堂內(nèi)的尸體忽然破棺而出府蛇,到底是詐尸還是另有隱情,我是刑警寧澤屿愚,帶...
    沈念sama閱讀 35,731評(píng)論 5 346
  • 正文 年R本政府宣布汇跨,位于F島的核電站务荆,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏扰法。R本人自食惡果不足惜蛹含,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,348評(píng)論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望塞颁。 院中可真熱鬧,春花似錦吸耿、人聲如沸祠锣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,929評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)伴网。三九已至,卻和暖如春妆棒,著一層夾襖步出監(jiān)牢的瞬間澡腾,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,048評(píng)論 1 270
  • 我被黑心中介騙來(lái)泰國(guó)打工糕珊, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留动分,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,203評(píng)論 3 370
  • 正文 我出身青樓红选,卻偏偏與公主長(zhǎng)得像澜公,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子喇肋,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,960評(píng)論 2 355

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

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi閱讀 7,332評(píng)論 0 10
  • #尊重資本量級(jí)的差異# 在自我大腦升級(jí)迭代的過(guò)程中坟乾,如何對(duì)待資本量級(jí)間存在的差異: 1、不找借口 所謂找借口蝶防,就是...
    耿孝意閱讀 235評(píng)論 0 0
  • 在一家港市甜品店工作過(guò)一段時(shí)間间学,店里主要是芒果和榴蓮的甜品殷费。我的工作里有一部分的職責(zé)就是翻撿芒果,因?yàn)槊⒐墒斓暮?..
    放羊的老奶奶閱讀 1,507評(píng)論 0 12
  • 離開那座島嶼 仿佛離開一場(chǎng)宿命 消失在黎明之前 眼淚的速度趕不上高鐵 你在第四座城里等我 攜了漂洋過(guò)海的宇宙 我開...
    刺猬小姐木果果閱讀 253評(píng)論 1 3