In one of the interview I was asked how to get all combinations of vector<vector<int>>
Anonymous User
219

I am trying to write a function which has the below declaration,

vector<vector<int>> getAllCombinations(vector<vector<int>> input);

Example input 1: If my input is [[1,2],[3,4]], the expected output is [[1,3],[1,4],[2,3],[2,4]]. We need to get all combinations of all indexes of vector.

Example input 2: If my input is [[1,2],[3,4,5]], the expected output is [[1,3],[1,4],[1,5],[2,3],[2,4],[2,5].

Example input 3: If my input is [[0,9],[1,2],[3,4,5]], the expected output is [[0,1,3],[0,1,4],[0,1,5],[0,2,3],[0,2,4],[0,2,5],[9,1,3],[9,1,4],[9,1,5],[9,2,3],[9,2,4],[9,2,5].

The input can have any variable size of vector.

I could have used Java too with below declaration.

public static List<List<Integer>> getAllCombinations(List<List<Integer>> vals)

I did not get the output in the interview but I am trying to write a recurssive approach now for practice, but am struck with below implementation,

	public static List<List<Integer>> getAllCombinations(List<List<Integer>> vals)
	{
		List<List<Integer>> res = new ArrayList<List<Integer>>();
		if(vals.size() == 1) {
			for(int i=0; i<vals.get(0).size();++i) {
				List<Integer> temp = new ArrayList<Integer>();
				temp.add(vals.get(0).get(i));
				res.add(temp);
			}
		}
		else {		
			for(int i=0; i<vals.get(index))
			res = getAllCombinations(vals.subList(1, vals.size()));
		}
		return res;
	}
Comments (2)