給出一個set的字元和一個正數k,求所有由這個set能組成長度為k的字串集合 print-all-combinations-of-given-length

來源:互聯網
上載者:User

給出一個set的字元和一個正數k,求所有由這個set能組成長度為k的字串集合 print-all-combinations-of-given-length

// 給出一個set的字元和一個正數k,求所有由這個set能組成長度為k的字串集合

/*

Input: 

set[] = {'a', 'b'}, k = 3

Output:

aaa

aab

aba

abb

baa

bab

bba

bbb

Input: 

set[] = {'a', 'b', 'c', 'd'}, k = 1

Output:

a

b

c

d



package recursion;import java.util.ArrayList;public class N_sets_form_length_k_string {// 給出一個set的字元和一個正數k,求所有由這個set能組成長度為k的字串集合/* Input: set[] = {'a', 'b'}, k = 3Output:aaaaababaabbbaababbbabbbInput: set[] = {'a', 'b', 'c', 'd'}, k = 1Output:abcd  */public static void main(String[] args) {ArrayList<Character> set = new ArrayList<Character>();set.add('a');set.add('b');int k = 3;ArrayList<String> al = new ArrayList<String>();StringBuilder sb = new StringBuilder();rec(set, k, al, sb);System.out.println(al);}// 觀察到選定第一個字元後,問題就轉化為k-1的遞迴問題,而set中的每一個元素都能充當第一個字元。// 結束條件就是k為0時。public static void rec(ArrayList<Character> set, int k, ArrayList<String> al, StringBuilder sb){if(k == 0) {al.add(new String(sb));return;}for(int i=0; i<set.size(); i++) {sb.append(set.get(i));rec(set, k-1, al, sb);sb.deleteCharAt(sb.length()-1);// 善用StringBuilder來刪除最後一個字元}}}

http://www.geeksforgeeks.org/print-all-combinations-of-given-length/

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.