[LeetCode][JavaScript]Combination Sum III

來源:互聯網
上載者:User

標籤:

Combination Sum III

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.


Example 1:

Input: k = 3, n = 7

Output:

[[1,2,4]]

 

Example 2:

Input: k = 3, n = 9

Output:

[[1,2,6], [1,3,5], [2,3,4]]

https://leetcode.com/problems/combination-sum-iii/

 


 


我做到現在AC最快的題目,真的不到1分鐘,還是上兩題的變通:

http://www.cnblogs.com/Liok3187/p/4526863.html

http://www.cnblogs.com/Liok3187/p/4532064.html

把第二題的代碼copy過來,刪掉visited,candidates換成一到9,最後加上個數的限制,就好了。

真會玩啊,一個類型翻來覆去,很歡迎Combination Sum IV

 1 /** 2  * @param {number} k 3  * @param {number} n 4  * @return {number[][]} 5  */ 6 var combinationSum3 = function(k, n) { 7     var res = []; 8     var candidates = [1,2,3,4,5,6,7,8,9]; 9     candidates.sort(sorting);10     bfs(0, -1, []);11     return res;12 13     function bfs(sum, index, tmp){14         var newTmp = null;15         if(sum === n && tmp.length === k){16             newTmp = tmp.concat();17             res.push(newTmp);18             return;19         }else if(tmp.length > k || sum > n || index + 1 >= candidates.length){20             return; //pruning21         }22 23         for(var i = index + 1; i < candidates.length; i++){24             newTmp = tmp.concat();25             newTmp.push(candidates[i]);26             bfs(sum + candidates[i], i, newTmp);27         }28     }29     function sorting(a, b){30         if(a > b){31             return 1;32         }else if(a < b){33             return -1;34         }else{35             return 0;36         }37     }38 };

 

 

[LeetCode][JavaScript]Combination Sum III

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.