[Twitter] All possible pickings

Question: 

Given n sets of choices: (1, 2, 3), (a, b, c), (i, ii, iii).

You pick one element from each set of choices. Generate all possible pickings. 

http://www.glassdoor.com/Interview/Given-n-sets-of-choices-1-2-3-2-3-4-4-5-You-pick-one-element-from-each-set-of-choices-Generate-all-possibl-QTN_218899.htm


private List<List<String>> generateAllPickings(String[][] pool)
{
    List<List<String>> result = new ArrayList<>();
    help(pool, 0, new ArrayList<String>(), result);
    return result;
}

private void help(String[][] pool, 
                  int group,
                  List<String> cur,
                  List<List<String>> result)
{
    if (cur.size() == pool.length)
    {
        result.add(new ArrayList<String>(cur));
    }
    if (group >= pool.length)
    {
        return;
    }
    
    // Now we are looking at pool[group], put each elements into the cur
    for (int i = 0 ; i < pool[group].length ; i ++)
    {
        cur.add(pool[group][i]);
        help(pool, group + 1, cur, result);
        cur.remove(cur.size() - 1);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章